UnauthorizedAccessException on MemoryMappedFile in C# 4

久未见 提交于 2019-12-04 00:28:51

问题


I wanted to play around with using a MemoryMappedFile to access an existing binary file. If this even at all possible or am I a crazy person?

The idea would be to map the existing binary file directly to memory for some preferably higher-speed operations. Or to atleast see how these things worked.

        using System.IO.MemoryMappedFiles;


        System.IO.FileInfo fi = new System.IO.FileInfo(@"C:\testparsercap.pcap");
        MemoryMappedFileSecurity sec = new MemoryMappedFileSecurity();
        System.IO.FileStream file = fi.Open(System.IO.FileMode.Open, System.IO.FileAccess.ReadWrite, System.IO.FileShare.ReadWrite);
        MemoryMappedFile mf = MemoryMappedFile.CreateFromFile(file, "testpcap", fi.Length, MemoryMappedFileAccess.Read, sec, System.IO.HandleInheritability.Inheritable, true);
        MemoryMappedViewAccessor FileMapView = mf.CreateViewAccessor();
        PcapHeader head = new PcapHeader();
        FileMapView.Read<PcapHeader>(0, out head);

I get System.UnauthorizedAccessException was unhandled (Message=Access to the path is denied.) on the mf.CreateViewAccessor() line.

I don't think it's file-permissions, since I'm running as a nice insecure administrator user, and there aren't any other programs open that might have a read-lock on the file. This is on Vista with UAC disabled.

If it's simply not possible and I missed something in the documentation, please let me know. I could barely find anything at all referencing this feature of .net 4.0

Thanks!


回答1:


I know this is an old question, but I just ran into the same error and was able to solve it.

Even though I was opening the MemoryMappedFile as read-only (MemoryMappedFileRights.Read) as you are, I also needed to create the view accessor as read-only as well:

var view = mmf.CreateViewAccessor(offset, size, MemoryMappedFileAccess.Read);

Then it worked. Hope this helps someone else.




回答2:


If the size is more than the file length, it gives the UnAuthorized Access exception. Because we are trying to access memory beyond the limits of the file.

var view = mmf.CreateViewAccessor(offset, size, MemoryMappedFileAccess.Read);



回答3:


It is difficult to say what might be going wrong. Since there is no documentation on the MSDN website yet, your best bet is to install FILEMON from SysInternals, and see why that is happening.

Alternately, you can attach a native debugger (like WinDBG) to the process, and put a breakpoint on MapViewOfFile and other overloads. And then see why that call is failing.




回答4:


Using the .CreateViewStream() from the instance of MemoryMappedFile removed the error from my code. I was unable to get .CreateViewAcccessor() working w/the access denied error



来源:https://stackoverflow.com/questions/1220913/unauthorizedaccessexception-on-memorymappedfile-in-c-sharp-4

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!