如何在 C# 中開啟純文字檔案?


要開啟純文字檔案,請使用 StreamReader 類。以下是開啟檔案進行讀取的操作−

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

現在,顯示檔案內容−

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

以下是程式碼 −

示例

 線上演示

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();
      }
   }
}

輸出

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

更新日期: 22-Jun-2020

250 次瀏覽

開啟您的職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.