使用 StreamReader 在 C# 中读取文件

csharpprogrammingserver side programming更新于 2025/8/23 0:37:17

要读取文本文件,请使用 C# 中的 StreamReader 类。

添加要读取的文件名 −

StreamReader sr = new StreamReader("hello.txt");

使用 ReadLine() 方法并以字符串形式获取文件内容 −

using (StreamReader sr = new StreamReader("hello.txt")) {
   str = sr.ReadLine();
}
Console.WriteLine(str);

我们来看以下代码 −

示例

using System.IO;
using System;

public class Program {
   public static void Main() {
      string str;
      using (StreamWriter sw = new StreamWriter("hello.txt")) {
         sw.WriteLine("Hello");
         sw.WriteLine("World");
      }
      using (StreamReader sr = new StreamReader("hello.txt")) {
         str = sr.ReadLine();
      }
      Console.WriteLine(str);
   }
}

它会创建文件"hello.text"并向其中添加文本。之后,它会使用 StreamReader 类读取文件的第一行 −

输出

以下是输出。

Hello

相关文章