I am currently creating a user control that holds an UploadedImage property of type System.Drawing.Image.
I read the other posts about this error, but they all say that I have to close the stream. However, I am not using the stream :(
I use the code below when a file is uploaded:
/// <summary>
/// Invoked when the image uploader uploaded a new file
/// </summary>
/// <param name="sender">Sender</param>
/// <param name="args">UploaderEventArgs</param>
protected void imageUploader_FileUploaded(object sender, UploaderEventArgs args)
{
try
{
// Store image
/*using (Stream stream = args.OpenStream())
{
_uploadedImage = new System.Drawing.Bitmap(stream);
_uploadedImage.Save(args.GetTempFilePath());
}*/
// Delay the deletion of the temp file with an hour
args.Persist();
// Save the file as image
_uploadedImage = System.Drawing.Image.FromFile(args.GetTempFilePath());
// Invoke event
OnImageUploaded(args.FileGuid);
}
catch (Exception)
{
args.Delete();
}
}
Simply said, I use args.Persist() to keep the file on disk for another hour (as described in another post). Then, I load the image into memory so I can easily retrieve it when I have to using the UploadedImage property.
Finally, the OnImageUploaded invokes a custom event and calls an image handler with the file guid. In the handler, I use this code to load the image into the handler:
/// <summary>
/// Retrieves an image from disk
/// </summary>
/// <param name="objectID">ID of the object to retrieve</param>
/// <returns>Image based on the object ID</returns>
protected override System.Drawing.Image GetImage(string objectID)
{
// Check the data
if (string.IsNullOrEmpty(objectID))
{
// Failed
return null;
}
// Get the guid
Guid guid = new Guid(objectID);
// Get all the files
try
{
string[] files = Directory.GetFiles(HttpContext.Current.Server.MapPath(_uploadPath),
string.Format("persisted.{0}.*", guid), SearchOption.AllDirectories);
if (files.Length == 0)
{
// Failed
return null;
}
// Return the image
return System.Drawing.Image.FromFile(files[0]);
}
catch (Exception)
{
// Failed
return null;
}
}
The exception does not occur consequently, only now and then. What am I doing wrong?
Thanks in advance!