Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/332.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/heroku/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 在不移动位置的情况下向MemoryStream追加字节_C#_Memorystream - Fatal编程技术网

C# 在不移动位置的情况下向MemoryStream追加字节

C# 在不移动位置的情况下向MemoryStream追加字节,c#,memorystream,C#,Memorystream,我试图用Write()将数据附加到MemoryStream;方法 但这也改变了立场。我知道我可以手动改变位置。 但是有没有一种方法可以在不移动位置的情况下将数据追加到MemoryStream中 using (MemoryStream stream = new MemoryStream()) using (BinaryReader reader = new BinaryReader(stream)) { byte[]

我试图用Write()将数据附加到MemoryStream;方法 但这也改变了立场。我知道我可以手动改变位置。 但是有没有一种方法可以在不移动位置的情况下将数据追加到MemoryStream中

using (MemoryStream stream = new MemoryStream())
            using (BinaryReader reader = new BinaryReader(stream))
            {
                byte[] data = new byte[20];
                Random rand = new Random();
                rand.NextBytes(data);

                stream.Write(data, 0, 20);
                Console.WriteLine(reader.ReadInt32());//Pointer = 20 here
            }

谢谢

不,MemoryStream本身没有任何功能可以做到这一点。对于流,这也是逻辑行为

但这也意味着,如果你自己做这件事,没有什么错。如果您想用某种好方法重用此功能,我建议您为
MemoryStream
编写一个简单的扩展方法:

public static class Extensions
{
    public static void WriteAndResetPosition(this MemoryStream stream, byte[] data, int offset, int count)
    {
        stream.Write(data, offset, count);
        stream.Position -= count;
    }    
} 
这是大脑编译的代码:),所以要谨慎对待。之后,您可以像这样使用它:

stream.WriteAndResetPosition(data, 0, 20);

不,MemoryStream本身没有任何功能来实现这一点。对于流,这也是逻辑行为

但这也意味着,如果你自己做这件事,没有什么错。如果您想用某种好方法重用此功能,我建议您为
MemoryStream
编写一个简单的扩展方法:

public static class Extensions
{
    public static void WriteAndResetPosition(this MemoryStream stream, byte[] data, int offset, int count)
    {
        stream.Write(data, offset, count);
        stream.Position -= count;
    }    
} 
这是大脑编译的代码:),所以要谨慎对待。之后,您可以像这样使用它:

stream.WriteAndResetPosition(data, 0, 20);

否,读或写逻辑上前进当前位置。如果您想要并且流支持,您可以通过写入的字节数将其设置回原来的位置。不,读或写逻辑上会使当前位置提前。如果这是您想要的并且流支持它,您可以通过写入的字节数将其设置回原来的值。。。我的总是包含递归。@ShannonHolsinger只要它不是大脑执行的,就可以了!大脑编译代码。。。我的总是包含递归。@ShannonHolsinger只要它不是大脑执行的,就可以了!