Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UnauthorizedAccessException on MemoryMappedFile in C# 4

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!

like image 808
Kevin Nisbet Avatar asked Aug 03 '09 06:08

Kevin Nisbet


1 Answers

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.

like image 183
PatrickSteele Avatar answered Oct 21 '22 20:10

PatrickSteele