The OpenText method opens an existing UTF-8 encoded text file for reading. The OpenText method takes a file name as a parameter and returns a StreamReader object.

StreamReader reader = fi.OpenText();

Once we have a StreamReader object, we can use its Read or ReadLine methods to read the contents. The ReadLine method reads one line at a time. The following code snippet loops through the entire content of a SteamReader and reads and prints one line at a time.

while ((s = reader.ReadLine()) != null)
{
	Console.WriteLine(s);
}

The following lists the complete code sample.

string fileName = @"C:\fileName.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 (StreamReader reader = fi.OpenText())
	{
		string s = "";
		while ((s = reader.ReadLine()) != null)
		{
			Console.WriteLine(s);
		}
	}
}
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

vote
Article Rating
Xem thêm  [C#] How to use File.OpenWrite Method

By admin

Theo dõi
Thông báo khi
guest
1 Comment
cũ nhất
mới nhất đánh giá nhiều nhất
Inline Feedbacks
View all comments
trackback

[…] [C#] How to use File.OpenText Method […]

1
0
Would love your thoughts, please comment.x
()
x