This is a mirror of official site: http://jasper-net.blogspot.com/

How to create a memory mapped file with C# (Windows Vista / Windows 7)

| Wednesday, October 5, 2011
Hi all,

 

The following C# sample shows how to create a memory mapped file and use private namespaces to allow access to specific groups of users:

 

FORM1.CS

using System;
 using System.Collections.Generic;
 using System.ComponentModel;
 using System.Data;
 using System.Drawing;
 using System.Linq;
 using System.Text;
 using System.Windows.Forms;
 using System.Runtime.InteropServices;
 using System.Security.Principal;
 using System.IO;
 
 namespace Alejacma
 {

 public partial class Form1 : Form
 {
 public Form1()
 {
 InitializeComponent();
 }
 
 private void button1_Click(object sender, EventArgs e)
 {
 bool bResult = false;
 IntPtr hBoundary = IntPtr.Zero;
 IntPtr pSid = IntPtr.Zero;
 int cbSid = Win32.SECURITY_MAX_SID_SIZE;
 IntPtr hNamespace = IntPtr.Zero;
 Win32.SECURITY_ATTRIBUTES securityAttributes = new Win32.SECURITY_ATTRIBUTES();
 IntPtr hFile = IntPtr.Zero;
...
...

// Create file mapping, and give access to all users with access to the namespace
 hFile = Win32.CreateFileMapping(
 Win32.INVALID_HANDLE_VALUE,
 ref securityAttributes,
 Win32.PAGE_READWRITE,
 0,
 20971520,
 "Alejacma\\TestFileMapping"
 );

 if (hFile == IntPtr.Zero) { throw new Exception("CreateFileMapping", new Win32Exception(Marshal.GetLastWin32Error())); }
 
 // Map file and write something to it
 pView = Win32.MapViewOfFile(
 hFile,
 Win32.FILE_MAP_WRITE,
 0,
 0,
 11
 );

 if (pView == IntPtr.Zero) { throw new Exception("MapViewOfFile", new Win32Exception(Marshal.GetLastWin32Error())); }
 
 pData = Marshal.StringToHGlobalAnsi("Hello World");
 Win32.MemCopy(pView, pData, 11);


Read more: Decrypt my World
QR: how-to-create-a-memory-mapped-file-with-c-windows-vista-windows-7.aspx

Posted via email from Jasper-net

0 comments: