Monday, 23 July 2012

.Net Tip , C# Tip : Copy one stream to another stream Using CopyTo Method with C# Examples and VB.Net Examples

.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.
You can also say that write content or data of one stream to another stream.

Here is example of this.
In this example we copy FileStream content to MemoryStream. We first create file stream object and print it's length after that we copy filestream object to memorystrem object and print it's length. You can see output in below image.

C# Example :
        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
        Response.Write(string.Format("MemoryStream Content length: {0}", objMemoryStream.Length.ToString()));
        Response.Write("<br/><br/>"); Example :
        Dim objFileStream As FileStream = File.Open(Server.MapPath("TextFile.txt"), FileMode.Open)
        Response.Write(String.Format("FileStream Content length: {0}", objFileStream.Length.ToString()))

        Dim objMemoryStream As New MemoryStream()

        ' Copy File Stream to Memory Stream using CopyTo method
        Response.Write(String.Format("MemoryStream Content length: {0}", objMemoryStream.Length.ToString()))
Output :

This type of C# Tips is very useful in day to day programming life.

Note : Give Us your valuable feedback in comments. Give your suggestions in this article so we can update our articles accordingly that.


  1. This is an amazing blog,it gives very helpful messages to us.Besides that Wisen has established as Best Dot Net Training in Chennai. or learn thru ASP.NET Online Training . Nowadays Dot Net has tons of job opportunities on various vertical industry.

  2. This blog gives very important info about .Net Thanks for sharing
    .Net Online Training Hyderabad