如何在 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.