Search code examples
c#fileopenfiledialog

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 works 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?


Solution

  • 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.