Social Media | Online Marketing | Digital Media | Daydev

Friday, May 18th

Last update:09:01:51 PM GMT

Headlines:

You are here: Home Category Blog ASP.NET C# วิธีอ่าน Text File

ASP.NET C# วิธีอ่าน Text File

E-mail Print PDF

เมื่อ เขียนโปรแกรมบ่อยครั้งที่เราต้องการอ่านแฟ้มที่เก็บตัวอักษรล้วนๆ หรือ text file เพื่ออ่านข้อมูลบางอย่างที่มีขนาดเล็กและทำงานได้รวดเร็ว โค้ดต่อไปนี้อ่านไฟล์ชื่อ Data.txt ซึ่งอยู่ที่รูทไดเรคทอรีของฮาร์ดดิสก์ (โฟลเดอร์ c:\) หัวใจของการทำงานคือการเรียกใช้ไทป์ StreamReader ของ .Net

public class FileClass
{
public static void Main()
{
ReadFromFile("c:\\data.txt");
}
static void ReadFromFile(string filename)
{
StreamReader SR;
string S;
SR = File.OpenText(filename);
S = SR.ReadLine();
while (S != null)
{
Console.WriteLine(S);
S = SR.ReadLine();
}
SR.Close();
}
}

Powered by Web Agency
comments

Comments and Reviews