写入字符串数据MemoryMappedFile(Write string data to M

2019-07-29 15:39发布

我下面这个教程在这里

我有一个很难搞清楚如何得到一个字符串“这是一个测试邮件”中的内存映射文件来存储,然后拉出来的另一边。 本教程说,使用字节数组。 原谅我是新来这个,并试图对我自己的第一次。

谢谢,凯文

##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();
    }
}

Answer 1:

你可以考虑写入字符串的长度,那么你的字符串的字节[]的形式。
例如,如果我想写“你好”,然后我把它转换成字节:

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

然后同时写入到内存映射文件做以下。

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

在阅读先去位置54和读取2个字节牵着你的字符串的长度。 然后你就可以读取长度的数组,并将其转换成字符串。

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));


文章来源: Write string data to MemoryMappedFile