Cannot delete file for MemoryMappedFile

The following code throws this exception:

"The process cannot access the file '\ filename' because it is being used by another process.

Fair enough, but what is the right way to close the reader and / or mmf so that the file can be deleted? I would think that a MemoryMappedFile would have a close () method or something like that, but that is not the case.

Any help would be greatly appreciated. Thank.

mmf = MemoryMappedFile.CreateFromFile(filename,
      System.IO.FileMode.OpenOrCreate,
      "myMap" + fileNo.ToString(),
      fileSize);

reader = mmf.CreateViewAccessor(0, accessorSize);

<do stuff>

File.Delete(filename);

edits:

It seems that only in the destructor do I have this problem. When dispose () is called elsewhere, it works fine, but when I do the following, it throws an exception. Readers and mmf are obviously members of the class. Does something implicit happen to access the file after entering the constructor?

~Class()
{
    try
    {
        if (File.Exists(filename))
        {
            reader.Dispose();
            mmf.Dispose();
            File.Delete(filename);
        }
    }
    catch (Exception e)
    {
    }
}
+5
2

using, :

using (var mmf = MemoryMappedFile.CreateFromFile(filename,
                   System.IO.FileMode.OpenOrCreate,
                   "myMap" + fileNo.ToString(), fileSize))
{
    using (reader = mmf.CreateViewAccessor(0, accessorSize))
    {  
       ... <do stuff> ...
    }
}

File.Delete(filename);

Dispose() reader mmf, using , , <do stuff> .

+4

:

reader.Dispose();
mmf.Dispose();
File.Delete(filename);
+3

All Articles