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.
string fileName = @"C:fileName.txt"; FileInfo fi = new FileInfo(fileName); FileStream fs = fi.OpenRead();
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.
using (FileStream fs = fi.OpenRead()) { 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:TempMaheshTXFITx.txt"; FileInfo fi = new FileInfo(fileName); // If file does not exist, create file if (!fi.Exists) { //Create the file. using (FileStream fs = fi.Create()) { Byte[] info = new UTF8Encoding(true).GetBytes("File Start"); fs.Write(info, 0, info.Length); } } try { using (FileStream fs = fi.OpenRead()) { 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()); }
NOTE:
A File must be opened using an IO resource before it can be read or write to. A file can be opened to read and/or write purpose. The FileInfo class provides four methods to open a file.
+ Open
+ OpenRead
+ OpenText
+ OpenWrite