Computer >> Máy Tính >  >> Lập trình >> C#

Làm thế nào để mở một tệp văn bản thuần túy trong C #?

Để mở một tệp văn bản thuần túy, hãy sử dụng lớp StreamReader. Phần sau sẽ mở một tệp để đọc -

StreamReader sr = new StreamReader("d:/new.txt")

Bây giờ, hãy hiển thị nội dung của tệp -

while ((line = sr.ReadLine()) != null) {
   Console.WriteLine(line);
}

Đây là mã -

Ví dụ

using System;
using System.IO;

namespace FileApplication {
   class Program {
      static void Main(string[] args) {
         try {

            using (StreamReader sr = new StreamReader("d:/new.txt")) {
               string line;

               // Read and display lines from the file until
               // the end of the file is reached.
               while ((line = sr.ReadLine()) != null) {
                  Console.WriteLine(line);
               }
            }
         } catch (Exception e) {
            // Let the user know what went wrong.
            Console.WriteLine("The file could not be read:");
            Console.WriteLine(e.Message);
         }
         Console.ReadKey();
      }
   }
}

Đầu ra

The file could not be read:
Could not find a part of the path "/home/cg/root/4281363/d:/new.txt".