Tuesday 19 June 2012

.Net Beginners , C# Tips : Read file with FileStream using Read method in C# .Net Programming and VB.Net Programming

You can read file byte data using "Read" Method of FileStream class and get bytes array. You can also say that read bytes array from FileStream object or read bytes array from FILE.

Here are example of this.
In this example We get FileStream of file and read it's byte data , byte data are store in Byte array.
You can also say that this approach is as chunk by chunk reading.

C# Example :
    // Get a filestream for reading a Text file
    System.IO.FileStream objFileStreamTxt = System.IO.File.OpenRead(MapPath("TextFile.txt"));

    // Set buffer length
    int intBufferLength = 16 * 1024;
    byte[] objBuffer = new byte[intBufferLength];

    int len = 0;

    while ((len = objFileStreamTxt.Read(objBuffer, 0, intBufferLength)) != 0)
    {
        // Here objBuffer object has bytes value, Which you can use to write into other stream or other use
        // Here objBuffer object contains intBufferLength length data
    }

    objFileStreamTxt.Close();

VB.net Example :
        ' Get a filestream for reading a Text file
        Dim objFileStreamTxt As System.IO.FileStream = System.IO.File.OpenRead(MapPath("TextFile.txt"))

        ' Set buffer length
        Dim intBufferLength As Integer = 16 * 1024
        Dim objBuffer As Byte() = New Byte(intBufferLength - 1) {}

        Dim len As Integer = 0
        len = objFileStreamTxt.Read(objBuffer, 0, intBufferLength)
        While len <> 0
            ' Here objBuffer object has bytes value, Which you can use to write into other stream or other use
            ' Here objBuffer object contains intBufferLength length data
            len = objFileStreamTxt.Read(objBuffer, 0, intBufferLength)
        End While

        objFileStreamTxt.Close()

In this example we read bytes array chunk by chunk , but If you want to get all bytes value whithout using loop than use this code.

C# Example (Without Loop) :
    System.IO.FileStream objFileStreamTmp = System.IO.File.OpenRead(MapPath("TextFile.txt"));
    byte[] objBufferTmp = new byte[objFileStreamTmp.Length];
    len = objFileStreamTmp.Read(objBufferTmp, 0, objBufferTmp.Length);

    objFileStreamTmp.Close();

VB.net Example (Without Loop) :
        Dim objFileStreamTmp As System.IO.FileStream = System.IO.File.OpenRead(MapPath("TextFile.txt"))
        Dim objBufferTmp As Byte() = New Byte(objFileStreamTmp.Length - 1) {}
        len = objFileStreamTmp.Read(objBufferTmp, 0, objBufferTmp.Length)

        objFileStreamTmp.Close()

Note : The chunk by chunk means looping approach is very good when you open a large file. Because if you open a large file in one statement it may gives Memory related errors.

This is very useful .Net Tips which is use in day to day programming life.


No comments:

Post a Comment