问题描述
以下代码引发此异常:
进程无法访问文件'\ filename',因为它正被另一个进程使用。
足够合理,但关闭读取器和/或mmf的正确方法是什么,以便文件可以被删除?我会认为,MemoryMappedFile将有一个close()方法或类似的东西,但它不。
任何帮助将不胜感激。
$ b
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 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的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!