我如何修改内存流中的一小部分字节,这是使用二进制文件编写的

时间:2016-05-28 17:23:45

标签: c# bytearray memorystream binarywriter

如何编辑内存流中的前四个字节?想象一下" bytes"在下面的代码中是几百字节长。我需要写一个占位符,比如4个字节的值为0,然后返回并将这些字节更新为新值。

static MemoryStream stream = new MemoryStream();
static BinaryWriter writer = new BinaryWriter(stream);

writer.Write(bytes);

1 个答案:

答案 0 :(得分:1)

这个解决方案怎么样:

static void UpdateNthLong(MemoryStream ms, long idx, long newValue)
{
    var currPos = ms.Position;
    try
    {
        var offset = sizeof(long) * idx;
        ms.Position = offset;
        var bw = new BinaryWriter(ms);
        bw.Write(newValue);
    }
    finally { ms.Position = currPos; }
}
static void ShowByteArray(byte[] array)
{
    Console.WriteLine("Size: {0}", array.Length);
    for(int i = 0; i < array.Length; i++)
    {
        Console.WriteLine("{0} => {1}", i, array[i]);
    }
}
static void Main(string[] args)
{
    using (var ms = new MemoryStream())
    {
        var bw = new BinaryWriter(ms);
        bw.Write(1L); // 0-th
        bw.Write(2L); // 1-th
        bw.Write(3L); // 2-th
        bw.Write(4L); // 3-th
        var bytes = ms.ToArray();

        Console.WriteLine("Before update:");
        ShowByteArray(bytes);
        // Update 0-th
        UpdateNthLong(ms, 0, 0xFFFFFFFFFFFFFF);
        // Update 3-th
        UpdateNthLong(ms, 3, 0xBBBBBBBBBBBBBBB);

        bytes = ms.ToArray();
        Console.WriteLine("After update:");
        ShowByteArray(bytes);
    }
}