Open a File in C#

File.Open Method

The Open method opens a FileStream on the specified file.

FileStream fs = File.Open(fileName, FileMode.Open, FileAccess.Write, FileShare.None);

File.OpenRead Method

The OpenRead method opens a file for reading. The method returns a FileStream object that is used to read a file using its Read method.

FileStream fs = File.OpenRead(fileName);

 

The file is read into a byte array. The following code snippet uses the FileStream.Read method and gets text into a byte array and then it is converted to a string using UTF8Encoding.GetString method.

byte[] byteArray = new byte[1024];

UTF8Encoding fileContent = new UTF8Encoding(true);

while (fs.Read(byteArray, 0, byteArray.Length) > 0)

{

    Console.WriteLine(fileContent.GetString(byteArray));

}

 

The following lists the complete code sample.

 

string fileName = @"C:\Temp\MaheshTXFI.txt";

try

{

    using (FileStream fs = File.OpenRead(fileName))

    {

        byte[] byteArray = new byte[1024];

        UTF8Encoding fileContent = new UTF8Encoding(true);

        while (fs.Read(byteArray, 0, byteArray.Length) > 0)

        {

            Console.WriteLine(fileContent.GetString(byteArray));

        }

    }

}

catch (Exception Ex)

{

    Console.WriteLine(Ex.ToString());

}

Up Next
    Ebook Download
    View all
    Learn
    View all