简体   繁体   English

我如何修改使用 binarywriter 写入的内存流中的一小部分字节

[英]how can i modify a small section of bytes in a memory stream, that was written to using binarywriter

how do i edit the first four bytes in memory stream?如何编辑内存流中的前四个字节? Imagine "bytes" in the following code is a few 100 bytes long.想象一下以下代码中的“字节”有几百个字节长。 i need to write a place holder of say, 4 bytes of value 0 and come back and update those bytes to new values.我需要编写一个占位符,例如 4 个字节的值 0,然后返回并将这些字节更新为新值。

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

writer.Write(bytes);

How about this solution:这个解决方案怎么样:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM