Can't delete file for MemoryMappedFile

点点圈 提交于 2020-01-03 13:39:07

问题


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)
    {
    }
}

回答1:


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




回答2:


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

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


来源:https://stackoverflow.com/questions/6481378/cant-delete-file-for-memorymappedfile

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!