无法删除MemoryMappedFile的文件 [英] Can't delete file for 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()
$ p $如果可能的话,您应该使用
{$ b $是否隐式发生文件访问b试试
{
if(File.Exists(filename))
{
reader.Dispose();
mmf.Dispose();
File.Delete(filename);
$ b catch(例外e)
{
}
}
结构:
解决方案 b
$ busing(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 thereader
andmmf
objects, howeverusing
will make sure that it is cleaned up in case exceptions are being thrown in<do stuff>
.这篇关于无法删除MemoryMappedFile的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文