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

后端 未结 13 2361
悲哀的现实
悲哀的现实 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:45

    There is actually, a less heavy-handed way of doing a stream copy. Take note however, that this implies that you can store the entire file in memory. Don't try and use this if you are working with files that go into the hundreds of megabytes or more, without caution.

    public static void CopySmallTextStream(Stream input, Stream output)
    {
      using (StreamReader reader = new StreamReader(input))
      using (StreamWriter writer = new StreamWriter(output))
      {
        writer.Write(reader.ReadToEnd());
      }
    }
    

    NOTE: There may also be some issues concerning binary data and character encodings.

    0 讨论(0)
  • 2020-11-21 22:47

    Since none of the answers have covered an asynchronous way of copying from one stream to another, here is a pattern that I've successfully used in a port forwarding application to copy data from one network stream to another. It lacks exception handling to emphasize the pattern.

    const int BUFFER_SIZE = 4096;
    
    static byte[] bufferForRead = new byte[BUFFER_SIZE];
    static byte[] bufferForWrite = new byte[BUFFER_SIZE];
    
    static Stream sourceStream = new MemoryStream();
    static Stream destinationStream = new MemoryStream();
    
    static void Main(string[] args)
    {
        // Initial read from source stream
        sourceStream.BeginRead(bufferForRead, 0, BUFFER_SIZE, BeginReadCallback, null);
    }
    
    private static void BeginReadCallback(IAsyncResult asyncRes)
    {
        // Finish reading from source stream
        int bytesRead = sourceStream.EndRead(asyncRes);
        // Make a copy of the buffer as we'll start another read immediately
        Array.Copy(bufferForRead, 0, bufferForWrite, 0, bytesRead);
        // Write copied buffer to destination stream
        destinationStream.BeginWrite(bufferForWrite, 0, bytesRead, BeginWriteCallback, null);
        // Start the next read (looks like async recursion I guess)
        sourceStream.BeginRead(bufferForRead, 0, BUFFER_SIZE, BeginReadCallback, null);
    }
    
    private static void BeginWriteCallback(IAsyncResult asyncRes)
    {
        // Finish writing to destination stream
        destinationStream.EndWrite(asyncRes);
    }
    
    0 讨论(0)
  • 2020-11-21 22:51

    Unfortunately, there is no really simple solution. You can try something like that:

    Stream s1, s2;
    byte[] buffer = new byte[4096];
    int bytesRead = 0;
    while (bytesRead = s1.Read(buffer, 0, buffer.Length) > 0) s2.Write(buffer, 0, bytesRead);
    s1.Close(); s2.Close();
    

    But the problem with that that different implementation of the Stream class might behave differently if there is nothing to read. A stream reading a file from a local harddrive will probably block until the read operaition has read enough data from the disk to fill the buffer and only return less data if it reaches the end of file. On the other hand, a stream reading from the network might return less data even though there are more data left to be received.

    Always check the documentation of the specific stream class you are using before using a generic solution.

    0 讨论(0)
  • 2020-11-21 22:54

    .NET Framework 4 introduce new "CopyTo" method of Stream Class of System.IO namespace. Using this method we can copy one stream to another stream of different stream class.

    Here is example for this.

        FileStream objFileStream = File.Open(Server.MapPath("TextFile.txt"), FileMode.Open);
        Response.Write(string.Format("FileStream Content length: {0}", objFileStream.Length.ToString()));
    
        MemoryStream objMemoryStream = new MemoryStream();
    
        // Copy File Stream to Memory Stream using CopyTo method
        objFileStream.CopyTo(objMemoryStream);
        Response.Write("<br/><br/>");
        Response.Write(string.Format("MemoryStream Content length: {0}", objMemoryStream.Length.ToString()));
        Response.Write("<br/><br/>");
    
    0 讨论(0)
  • 2020-11-21 22:55

    There may be a way to do this more efficiently, depending on what kind of stream you're working with. If you can convert one or both of your streams to a MemoryStream, you can use the GetBuffer method to work directly with a byte array representing your data. This lets you use methods like Array.CopyTo, which abstract away all the issues raised by fryguybob. You can just trust .NET to know the optimal way to copy the data.

    0 讨论(0)
  • 2020-11-21 22:56

    MemoryStream has .WriteTo(outstream);

    and .NET 4.0 has .CopyTo on normal stream object.

    .NET 4.0:

    instream.CopyTo(outstream);
    
    0 讨论(0)
提交回复
热议问题