gpt4 book ai didi

c# - 将字符串数据写入 MemoryMappedFile

转载 作者:太空狗 更新时间:2023-10-29 22:16:45 29 4
gpt4 key购买 nike

我正在学习本教程 here

我很难弄清楚如何将字符串“THIS IS A TEST MESSAGE”存储在内存映射文件中,然后将其从另一端拉出。本教程说使用字节数组。请原谅我,我是新手,先自己尝试。

谢谢,凯文

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

最佳答案

可以考虑先写字符串的长度,再写字符串的byte[]形式。
例如,如果我想写“Hello”,那么我将它转换成字节:

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

关于c# - 将字符串数据写入 MemoryMappedFile,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10806518/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com