如何在内存映射文件中写入冗长的字符串?

时间:2019-01-24 14:10:29

标签: c# memory-mapped-files memory-mapping

我在对象列表中有如下数据列表:

price:10, volumne:100, timestamp:1253568545
price:8, volumne:15, timestamp:4564546584545
price:68, volumne:846, timestamp:3548432545

所以现在我想将此数据写入到内存映射文件中,就像我在这里写的一样。像新行中的每个新符号信息一样。那怎么办呢?我在下面提到了我的代码,因此请帮助我解决这个问题。

using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(@"D:\data.txt", System.IO.FileMode.OpenOrCreate, "map1", 1000))
{
   using (MemoryMappedViewAccessor accessor = mmf.CreateViewAccessor())
   {
     foreach (var item in data.ticks)
     {
       byte[] data1 = Encoding.UTF8.GetBytes(item.t.ToString() + "," + item.p.ToString() + "," + item.s.ToString());
       accessor.WriteArray(0, data1, 0, data1.Length);
      }
    }
}```

In final I need a result like below so please help for solve it:
10,100,1253568545
8,15,4564546584545
68,846,3548432545


1 个答案:

答案 0 :(得分:1)

.WriteArray()方法的第一个参数是视图中必须开始写入的相对位置。每当您写了一些东西时,都必须根据所写的字节增加该光标。并且如果要写入的字节加上当前位置超出了当前窗口的大小,则必须在所需位置上创建一个新视图。这是一个示例:

var items = Enumerable.Range(1, 80).Select(i => new { Id = Guid.NewGuid(), Name = $"Item {i}" }).ToList();

using (var file = MemoryMappedFile.CreateFromFile(@"D:\data.txt", System.IO.FileMode.OpenOrCreate, "myMap", 4096))
{
    MemoryMappedViewAccessor accessor = null;
    // Small window size to enforce roll-over for testing.
    var windowSize = 100;
    var absolutePosition = 0;
    var relativePosition = 0;

    try
    {
        accessor = file.CreateViewAccessor(absolutePosition, windowSize, MemoryMappedFileAccess.ReadWrite);

        foreach (var item in items)
        {
            var value = $"{item.Id},{item.Name}{Environment.NewLine}";
            var bytes = Encoding.UTF8.GetBytes(value);

            if (bytes.Length + relativePosition > windowSize)
            {
                absolutePosition += relativePosition;
                relativePosition = 0;
                accessor.Dispose();
                accessor = file.CreateViewAccessor(absolutePosition, windowSize, MemoryMappedFileAccess.ReadWrite);
            }

            accessor.WriteArray(relativePosition, bytes, 0, bytes.Length);
            relativePosition += bytes.Length;
        }
    }
    finally
    {
        if (accessor != null)
            accessor.Dispose();
    }
}