Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do I need to dispose the FileStream object?

I am pretty depressed by my programming knowledge but do we really need to dispose FileStream Object ?

Reason I am asking is because code is throwing "File being used by another process" exception once in 100 cases and for a moment as if i try again(to download file using file stream) it works fine.

Please refer to this question for code.

Since it only happening once in 100 or so making me so confused and it's happening on production server so can't debug at all, but works perfectly on my development machine...

like image 728
Mathematics Avatar asked Sep 18 '13 11:09

Mathematics


People also ask

Do I need to dispose Streamreader?

Always call Dispose before you release your last reference to the TextReader. Otherwise, the resources it is using will not be freed until the garbage collector calls the TextReader object's Finalize method.

What is a FileStream object?

The FileStream is a class used for reading and writing files in C#. It is part of the System.IO namespace. To manipulate files using FileStream, you need to create an object of FileStream class. This object has four parameters; the Name of the File, FileMode, FileAccess, and FileShare.

What is object dispose?

The Dispose() methodThe Dispose method performs all object cleanup, so the garbage collector no longer needs to call the objects' Object. Finalize override. Therefore, the call to the SuppressFinalize method prevents the garbage collector from running the finalizer. If the type has no finalizer, the call to GC.

Does StreamWriter dispose stream?

StreamWriter. Dispose() does close the underlying stream.


1 Answers

Of course, you need to dispose everything that is disposable, unless you have very good reason to not to dispose.

Put everything into a using block by default. If you call Close manually this is a code smell.

like image 146
usr Avatar answered Sep 23 '22 05:09

usr