Why do files I have opened remain open unless I Dispose() them?
In my application, I am using OpenFileDialog and then assign the loaded file to LoadedFile field. I have found out that if I open 3 files, all remained open (access denied when trying to do anything with them) and I am not sure why? However when doing this, it wo开发者_JAVA百科rks fine:
if(LoadedFile!=null)
{
LoadedFile.Dispose();
LoadedFile=null;
}
LoadedFile=openFileDialog.GetFile() //pseudo code
Is it enough? Why all files remained "open" if I do not do that?
If you don't explicitly close an open file, it remains open and you get the access violation exception.
You should open the file within a using
statement in order to ensure that it is disposed of correctly (which is what your code does, manually).
using(File aFile = File.Open("path to file"))
{
// use the file
}
Note:
This has nothing to do with memory (which you don't control yourself, as .NET is garbage collected). It is about resource management, in this case open file handles.
Until you call Dispose()
(i.e., stating that you don't need it any more), the file will be locked.
You must close a file once you're done with it. Dispose
does that.
精彩评论