无法删除MemoryMappedFile的文件 [英] Can't delete file for MemoryMappedFile

查看:155
本文介绍了无法删除MemoryMappedFile的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码引发此异常:



进程无法访问文件'\ filename',因为它正被另一个进程使用。



足够合理,但关闭读取器和/或mmf的正确方法是什么,以便文件可以被删除?我会认为,MemoryMappedFile将有一个close()方法或类似的东西,但它不。



任何帮助将不胜感激。
$ b

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

reader = mmf.CreateViewAccessor(0,accessorSize);

<做东西>

File.Delete(filename);

EDITS:

看起来像是只有在析构函数,我有这个问题。当dispose()在其他地方被调用时,它可以正常工作,但是当我执行以下操作时,会抛出异常。 Reader和mmf显然是这个类的成员。

 〜Class()
{$ b $是否隐式发生文件访问b试试
{
if(File.Exists(filename))
{
reader.Dispose();
mmf.Dispose();
File.Delete(filename);

$ b catch(例外e)
{
}
}
结构:


解决方案 b
$ b

  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() code> reader 和 mmf 对象,但是使用会确保它在< do stuff> 中抛出异常的情况下进行清理。


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

解决方案

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

这篇关于无法删除MemoryMappedFile的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆