Writing String Data to a MemoryMappedFile

I follow this lesson here

It’s hard for me to figure out how to get the “THIS TEST MESSAGE” line to save the associated memory in a file, and then pull it out on the other side. The tutorial says using a byte array. Forgive me, I'm new to this and try on my own first.

Thanks Kevin

##Write to mapped file using System; using System.IO.MemoryMappedFiles; class Program1 { static void Main() { // create a memory-mapped file of length 1000 bytes and give it a 'map name' of 'test' MemoryMappedFile mmf = MemoryMappedFile.CreateNew("test", 1000); // write an integer value of 42 to this file at position 500 MemoryMappedViewAccessor accessor = mmf.CreateViewAccessor(); accessor.Write(500, 42); Console.WriteLine("Memory-mapped file created!"); Console.ReadLine(); // pause till enter key is pressed // dispose of the memory-mapped file object and its accessor accessor.Dispose(); mmf.Dispose(); } } ##read from mapped file using System; using System.IO.MemoryMappedFiles; class Program2 { static void Main() { // open the memory-mapped with a 'map name' of 'test' MemoryMappedFile mmf = MemoryMappedFile.OpenExisting("test"); // read the integer value at position 500 MemoryMappedViewAccessor accessor = mmf.CreateViewAccessor(); int value = accessor.ReadInt32(500); // print it to the console Console.WriteLine("The answer is {0}", value); // dispose of the memory-mapped file object and its accessor accessor.Dispose(); mmf.Dispose(); } } 
+5
source share
2 answers

You might consider writing the length of the string, and then the byte [] of your string.
For example, if I would like to write "Hello", then I will convert it to bytes:

 byte[] Buffer = ASCIIEncoding.ASCII.GetBytes("Hello"); 

then do the following when writing to a memory mapped file.

 MemoryMappedFile mmf = MemoryMappedFile.CreateNew("test", 1000); MemoryMappedViewAccessor accessor = mmf.CreateViewAccessor(); accessor.Write(54, (ushort)Buffer.Length); accessor.WriteArray(54 + 2, Buffer, 0, Buffer.Length); 

On first reading, go to position 54 and read 2 bytes while holding the length of your string. Then you can read an array of this length and convert it to a string.

 MemoryMappedFile mmf = MemoryMappedFile.CreateNew("test", 1000); MemoryMappedViewAccessor accessor = mmf.CreateViewAccessor(); ushort Size = accessor.ReadUInt16(54); byte[] Buffer = new byte[Size]; accessor.ReadArray(54 + 2, Buffer, 0, Buffer.Length); MessageBox.Show(ASCIIEncoding.ASCII.GetString(Buffer)); 
+12
source

I used this to write line characters:

 string contentString = "Hello"; char[] charsToWrite = contentString.ToCharArray(); accessor.WriteArray(0, charsToWrite, 0, charsToWrite.Length); 

It wrote wide characters. C # and C ++ programs could read data as wide characters.

0
source

Source: https://habr.com/ru/post/1414984/


All Articles