Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't 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's the proper way to close the reader and/or mmf so that the file can be deleted? I would think that MemoryMappedFile would have a close() method or something similar, but it doesn't.

Any help would be greatly appreciated. Thanks.

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

reader = mmf.CreateViewAccessor(0, accessorSize);

<do stuff>

File.Delete(filename);

EDITS:

It looks like it's only in the destructor that I'm having this problem. When dispose() is called elsewhere it works fine, but when I do the following it throws the exception. Reader and mmf are obviously members of the class. Is something implicit happening to the file access once the constructor is entered?

~Class()
{
    try
    {
        if (File.Exists(filename))
        {
            reader.Dispose();
            mmf.Dispose();
            File.Delete(filename);
        }
    }
    catch (Exception e)
    {
    }
}
like image 856
hdt Avatar asked Jun 26 '11 00:06

hdt


2 Answers

You should utilize the using construct if possible:

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);

Otherwise call Dispose() on the reader and mmf objects, however using will make sure that it is cleaned up in case exceptions are being thrown in <do stuff>.

like image 56
ChrisWue Avatar answered Sep 30 '22 05:09

ChrisWue


Prior to deleting the file, you must dispose of the mapping:

reader.Dispose();
mmf.Dispose();
File.Delete(filename);
like image 45
bdonlan Avatar answered Sep 30 '22 04:09

bdonlan