MemoryMappedFile.CreateFromFile 总是抛出 UnauthorizedAccessException
我意识到 .NET 4.0 处于 Beta 阶段,但我希望有人能解决这个问题。我正在尝试从 DLL 创建内存映射文件:
FileStream file = File.OpenRead("C:\mydll.dll");
using (MemoryMappedFile mappedFile = MemoryMappedFile.CreateFromFile(file,
"PEIMAGE", 1024 * 1024, MemoryMappedFileAccess.ReadExecute))
{
using (MemoryMappedViewStream viewStream = mappedFile.CreateViewStream())
{
// read from the view stream
}
}
不幸的是,无论我做什么,我总是收到 UnauthorizedAccessException
,为此 MSDN 文档 指出:
操作系统拒绝对文件的指定访问;例如,访问权限设置为“写入”或“读写”,但文件或目录是只读的。
我已经使用 Sysinternals Process Monitor 监视了我的应用程序,这表明该文件确实已成功打开。我还尝试过内存映射其他非 DLL 文件,但结果相同。
I realize .NET 4.0 is in Beta, but I'm hoping someone has a resolution for this. I'm trying to create a memory mapped file from a DLL:
FileStream file = File.OpenRead("C:\mydll.dll");
using (MemoryMappedFile mappedFile = MemoryMappedFile.CreateFromFile(file,
"PEIMAGE", 1024 * 1024, MemoryMappedFileAccess.ReadExecute))
{
using (MemoryMappedViewStream viewStream = mappedFile.CreateViewStream())
{
// read from the view stream
}
}
Unfortunately, no matter what I do, I always get an UnauthorizedAccessException
, for which the MSDN documentation states:
The operating system denied the specified access to the file; for example, access is set to Write or ReadWrite, but the file or directory is read-only.
I've monitored my application with Sysinternals Process Monitor, which shows that the file is indeed being opened successfully. I've also tried memory mapping other non-DLL files, but with the same result.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
好吧,我有一个基于上面的示例,它运行时没有异常。我做了两个重要的更改:
MemoryMappedFile
时指定了MemoryMappedFileAccess.Read
。您已将其打开以供阅读,因此您只能阅读。我还没有尝试通过更改 FileStream 的打开方式来修复它以允许执行。CreateViewStream
调用MemoryMappedFileAccess.Read
。我不确定为什么它本身不使用现有的访问权限,但我们就这样吧。完整程序:
Well, I've got an example based on the above which runs without exceptions. I've made two important changes:
MemoryMappedFileAccess.Read
when creating theMemoryMappedFile
. You've opened it for read, so you can only read. I haven't tried fixing it to allow execute as well by changing how theFileStream
is opened.CreateViewStream
call explicitly useMemoryMappedFileAccess.Read
as well. I'm not sure why it doesn't use the existing access rights by itself, but there we go.Full program:
调用 CreateViewAccessor(...) 方法时我有相同的行为。
事实证明,只有当大小参数超过文件长度时才会抛出错误(这与我们习惯的大小为最大值的流的行为不同,相反,它似乎将参数作为文字并且结果是尝试读取超过文件末尾的内容)。
我通过检查大小不超过打开文件的大小解决了我的问题。
I had the same behaviour when calling the CreateViewAccessor(...) method.
Turns out, the error was only thrown when the size parameter exceeded the length of the file (it's not the same behaviour as we're used to with streams where size is a maximum value, instead it appears to take the parameter as a literal and the result is an attempt to read past the end of the file).
I fixed my problem by checking that the size doesn't exceed the size of the open file.