dotnet / dotnet/dotnet-api-docs

Close stream sample

Open
#1,320 4 comments 0 reactions 0 assignees View on GitHub
area-System.Drawing dotnet-api/prod Pri2 untriaged
Dominant language
C#
Stars
949
Forks
1.7k
Avg merge
3d 27m
Merged PRs (30d)
49

Description

Your remarks say "You must keep the stream open for the lifetime of the Image.". So the following which is done in a lot of places I have seen in a lot of code bases is wrong.
```c#
Image GetImage(...){
Image img=null;
using (Stream strm = GetStream(...)){
img=Image.FromStream(strm);
}
return img;
}
```

I have suggested the following but it looks like it might not be enough.

```c#
using (Stream strm = GetStream(...)){
using (Image img=Image.FromStream(strm)){
return (Image) img.Clone();
}
}
```
So how do we use ImageFromStream and dispose of the stream and still have a good image object?

---
#### Document Details

⚠ *Do not edit this section. It is required for docs.microsoft.com ➟ GitHub issue linking.*

* ID: b805ea43-cf82-6ca1-51d3-ce74686cbbaa
* Version Independent ID: 09ac6cfa-b64c-8294-e73b-24a2aafad5f7
* Content: [Image.FromStream Method (System.Drawing)](https://docs.microsoft.com/en-us/dotnet/api/system.drawing.image.fromstream?view=netframework-4.7.2)
* Content Source: [xml/System.Drawing/Image.xml](https://github.com/dotnet/dotnet-api-docs/blob/master/xml/System.Drawing/Image.xml)
* Product: **dotnet-api**
* GitHub Login: @dotnet-bot
* Microsoft Alias: **dotnetcontent**

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.