Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does FileStream.Dispose close the file immediately?

Tags:

c#

.net

io

I have some code that writes a file by saving a MemoryStream to a FileStream using MemoryStream.WriteTo(). After the file is closed it is opened up again to read some metdata...

This works about 80 - 90% of the time. The other 20% I get an exception saying the file is "in use by another process".

Does FileStream.Dispose() not release resources synchronously? Is there something going on lower in Win32 land I'm not aware of? I'm not seeing anything obvious in the .Net documentation.

like image 897
Nate Avatar asked Jun 14 '11 21:06

Nate


People also ask

What does FileStream close () do?

Closes the current stream and releases any resources (such as sockets and file handles) associated with the current stream.

Do you need to dispose FileStream?

The general rule is to dispose everything that is disposable. In the specific case of a FileStream , you don't need to dispose it to close the file, you only need to use the Close method. You should however dispose of the FileStream object anyway, as it has a finalizer.

What should you do with a file stream when you are finished with it?

Always close a file stream when you are done reading data to help prevent data corruption.

Does StreamWriter dispose stream?

StreamWriter. Dispose() does close the underlying stream.


1 Answers

As "immediately" as possible. There can easily be some lag due to outstanding writes, delay in updating the directory info etc. It could also be anti-virus software checking your changed file.

This may be a rare case where a Thread.Sleep(1) is called for. But to be totally safe you will have to catch the (any) exception and try again a set number of times.

like image 82
Henk Holterman Avatar answered Sep 18 '22 22:09

Henk Holterman