Tuesday, 24 April 2012

Beginning .Net : Read a file using FileStream in C# Programming

There are many times you want to read text file.
There are many ways to read files. One way is to use FileStream class.
Here are sample example to read the file and display it's content on page.

C# Example :
        System.IO.FileStream fs = new System.IO.FileStream(Server.MapPath("TextFile.txt"),System.IO.FileMode.Open);
        byte[] data = new byte[fs.Length];
        fs.Read(data, 0, (int)fs.Length);
        Response.Write( System.Text.ASCIIEncoding.Default.GetString(data));

In this example creating a byte array the length of the stream, using the Length property to properly size the array, and then passing it to the Read method.
The Read method fills the byte array with the stream data, in this case reading the entire stream into the byte array. If you want to read only a chunk of the stream or to start at a specific point in the stream simply change the value of the parameters you pass to the Read method.

Streams must always be explicitly closed in order to release the resources they are using, which in this case is the file. Failing to explicitly close the stream can cause memory leaks, and it may also deny other users and applications access to the resource.

VB.net Example :
        Dim fs As New System.IO.FileStream(Server.MapPath("TextFile.txt"), System.IO.FileMode.Open)
        Dim data(fs.Length) As Byte
        fs.Read(data, 0, fs.Length)
        Response.Write(  ASCIIEncoding.Default.GetString(data) )

No comments:

Post a Comment