How do I copy the contents of one stream to another?

后端 未结 13 2381
悲哀的现实
悲哀的现实 2020-11-21 22:11

What is the best way to copy the contents of one stream to another? Is there a standard utility method for this?

13条回答
  •  一个人的身影
    2020-11-21 22:36

    if you want a procdure to copy a stream to other the one that nick posted is fine but it is missing the position reset, it should be

    public static void CopyStream(Stream input, Stream output)
    {
        byte[] buffer = new byte[32768];
        long TempPos = input.Position;
        while (true)    
        {
            int read = input.Read (buffer, 0, buffer.Length);
            if (read <= 0)
                return;
            output.Write (buffer, 0, read);
        }
        input.Position = TempPos;// or you make Position = 0 to set it at the start
    }
    

    but if it is in runtime not using a procedure you shpuld use memory stream

    Stream output = new MemoryStream();
    byte[] buffer = new byte[32768]; // or you specify the size you want of your buffer
    long TempPos = input.Position;
    while (true)    
    {
        int read = input.Read (buffer, 0, buffer.Length);
        if (read <= 0)
            return;
        output.Write (buffer, 0, read);
     }
        input.Position = TempPos;// or you make Position = 0 to set it at the start
    

提交回复
热议问题