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
        objFileStream.CopyTo(objMemoryStream);
        Response.Write("<br/><br/>");
        Response.Write(string.Format("MemoryStream Content length: {0}", objMemoryStream.Length.ToString()));
        Response.Write("<br/><br/>");

VB.net 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
        objFileStream.CopyTo(objMemoryStream)
        Response.Write("<br/><br/>")
        Response.Write(String.Format("MemoryStream Content length: {0}", objMemoryStream.Length.ToString()))
        Response.Write("<br/><br/>")
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 comment:

  1. First time here at your blog and wanted to say i enjoyed reading this

    ReplyDelete