views:

452

answers:

3

Hey,

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  A: 

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.

feroze
A: 

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

Mark
A: 

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.

Patrick Steele