Chia sẻ

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

ĐĂNG KÝ MUA HÀNG

    Email (*)

    Điện thoại (*)

    Tên sản phẩm/Dịch vụ:


    Chia sẻ
    Xem thêm  [C#] How to use FileInfo.Create Method

    Trả lời

    Email của bạn sẽ không được hiển thị công khai. Các trường bắt buộc được đánh dấu *