I have an application that is creating a number of images. After they have been created I try to FTP them to my webserver. This is done essentially by:
Each image is saved by:
1. Create a filestream
System.IO.FileStream fs = new System.IO.FileStream(Path + FileName, System.IO.FileMode.Create, System.IO.FileAccess.Write);
2. Save the image
Image.Save(fs, System.Drawing.Imaging.ImageFormat.Jpeg);
3. Close the filestream
fs.Dispose()
fs.Close();
Now, when i try to send them to my webserver, i use a class that opens a filestream by
input = New FileStream(FileName, FileMode.Open)
But this produces an exception:
IOException
The process cannot access the file '<filename>' because it is being used by another process.
If i create the images, restart the application and then tries to send them by ftp everything works fine, which must mean that the initial filestream, which were used for creating the images, doesn't release the file.
Shouldn't FileStream.Dispose() and FileStream.Close() release any resources

FileStream doesn't release resources
moerderin
SimonS_
Dim bmp As Image = Bitmap.FromFile("c:\temp\test2.bmp")
bmp.Save("c:\temp\test2.bmp")
And this code works:
Dim bmp As Image = Bitmap.FromFile("c:\temp\test2.bmp")
Dim cpy As New Bitmap(bmp)
bmp.Dispose()
cpy.Save("c:\temp\test2.bmp")
The Dispose call is critical, that seems to actually close the file handle.
ykgreene
lagu2653
Is there no way i can force a release of all resources of the file
Nguyen Duy Linh
I agree with nobugz
I actually had the same issue and he had responded and we agreed that it is most likely the Image/Bitmap not releasing the handle quick enough. hopefully a fix in SP1 next month :-)
its nothing to do with the filestream but the Bitmap object not releasing the resources quick enough. Even adding a delay wouldn't help much
JonathanMerrie
MaqboolHussain
Close and Dispose are the same for Stream and any class that inherits from it. So you only need to either call Close or Dipose although the second call is simply ignored so it doesn't really matter if you call both.
using (FileStream fs = new FileStream(@"c:\temp\somefile.dat", FileMode.Create))
{
// Write some content to the created file
}
Does the simplified example throw the exception If so I'd start looking for tools like antivirus software or desktop search tools to blame. Using FileMon or similiar tools is one way to try and find out what's going on.
cdemez
nice_boy_super
FileStream fs = new FileStream(Path + FileName, FileMode.Create, FileAccess.Write);
fs.Close();
fs.Dispose();
FileStream fs2 = new FileStream(Path + FileName, FileMode.Open);
fs2.Close();
fs2.Dispose();
DocMoriarty
just for testing, try adding a small delay after first dispose line.
system.threading.thread.sleep(300)