Calling FileContent locks file

classic Classic list List threaded Threaded
4 messages Options
Reply | Threaded
Open this post in threaded view
|  
Report Content as Inappropriate

Calling FileContent locks file

Guest-1063

I'm trying to convert an uploaded file into an Image object, so I can resize it before saving. However, the following line causes an error:

System.Drawing.Image profileImg = System.Drawing.Image.FromStream(ProfileImg.FileContent);

Error is:

The process cannot access the file because it is being used by another process.

How do I convert the uploaded file into an Image object?

Reply | Threaded
Open this post in threaded view
|  
Report Content as Inappropriate

Re: Calling FileContent locks file

Guest-1063

I was able to get it to work using this slightly modified code:

Stream imgStream = ProfileImg.FileContent;

System.Drawing.Image profileImg = System.Drawing.Image.FromStream(imgStream);

Not entirely sure what the difference is, as it's basically the same code. Any idea why this works and the other doesn't?

Reply | Threaded
Open this post in threaded view
|  
Report Content as Inappropriate

Re: Calling FileContent locks file

Dean Brettle
Administrator
Regardless of which way you do it, I think you will sometimes get that error because you didn't close the Stream.  Add:

imgStream.Close()

at the end to fix that.

--Dean
Reply | Threaded
Open this post in threaded view
|  
Report Content as Inappropriate

Re: Calling FileContent locks file

Guest-1063

You're right. I was closing the stream on the second example, but not on the first.

Here is the fix for the first example:

System.Drawing.Image profileImg = System.Drawing.Image.FromStream(ProfileImg.FileContent);

ProfileImg.FileContent.Close(); // this closes the stream

Loading...