无法删除 MemoryMappedFile 的文件
以下代码抛出此异常:
“该进程无法访问文件 '\filename',因为它正在被另一个进程使用。”
很公平,但是关闭阅读器和/或 mmf 以便删除文件的正确方法是什么?我认为 MemoryMappedFile 会有一个 close() 方法或类似的方法,但事实并非如此。
任何帮助将不胜感激。谢谢。
mmf = MemoryMappedFile.CreateFromFile(filename,
System.IO.FileMode.OpenOrCreate,
"myMap" + fileNo.ToString(),
fileSize);
reader = mmf.CreateViewAccessor(0, accessorSize);
<do stuff>
File.Delete(filename);
编辑:
看起来只有在析构函数中我才遇到这个问题。当在其他地方调用 dispose() 时,它工作正常,但是当我执行以下操作时,它会抛出异常。 Reader和mmf显然是该类的成员。输入构造函数后,文件访问是否会发生隐含的情况?
~Class()
{
try
{
if (File.Exists(filename))
{
reader.Dispose();
mmf.Dispose();
File.Delete(filename);
}
}
catch (Exception e)
{
}
}
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)
{
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果可能,您应该使用
using
构造:否则,请在
reader
和mmf
对象上调用Dispose()
using
将确保在
中抛出异常时将其清除。You should utilize the
using
construct if possible: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>
.在删除文件之前,您必须处理映射:
Prior to deleting the file, you must dispose of the mapping: