StreamReader和StreamWriter类用于从文本文件读取和写入数据。这些类继承自抽象基类Stream,它支持读取和写入文件流中的字节。
StreamReader类
StreamReader类是从抽象基类TextReader继承,它也是一个读取系列字符的读取器。 下表介绍了StreamReader类的一些常用方法:
| 序号 | 方法 | 描述 | 
|---|---|---|
| 1 | public override void Close() | 它关闭 StreamReader对象和底层流,并释放与读取器相关联的任何系统资源。 | 
| 2 | public override int Peek() | 返回下一个可用字符,但不消耗它。 | 
| 3 | public override int Read() | 从输入流读取下一个字符,并将字符位置提前一个。 | 
示例
以下示例演示如何C#程序读取一个名称为Jamaica.txt的文本文件,该文件内容如下所示:
using System;
using System.IO;
namespace FileApplication
{
   class Program
   {
      static void Main(string[] args)
      {
         try
         {
            // Create an instance of StreamReader to read from a file.
            // The using statement also closes the StreamReader.
            using (StreamReader sr = new StreamReader("c:/jamaica.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();
      }
   }
}
在编译和运行程序时,猜一下它显示的内容 -
StreamWriter类
StreamWriter类继承自抽象类TextWriter表示一个写入器,可以编入序列字符。
下表描述了此类最常用的方法:
| 序号 | 方法 | 描述 | 
|---|---|---|
| 1 | public override void Close() | 关闭当前 StreamWriter对象和底层流。 | 
| 2 | public override void Flush() | 清除当前写入程序的所有缓冲区,并将任何缓冲的数据写入底层流。 | 
| 3 | public virtual void Write(bool value) | 将布尔值的文本表示写入文本字符串或流(从 TextWriter继承) | 
| 4 | public override void Write(char value) | 将字符写入流 | 
| 5 | public virtual void Write(decimal value) | 将十进制值的文本表示形式写入文本字符串或流。 | 
| 6 | public virtual void Write(double value) | 将 8字节浮点值的文本表示写入文本字符串或流。 | 
| 7 | public virtual void Write(int value) | 将 4字节有符号整数的文本表示写入文本字符串或流。 | 
| 8 | public override void Write(string value) | 将一个字符串写入流。 | 
| 9 | public virtual void WriteLine() | 将行终止符写入文本字符串或流。 | 
有关方法的完整列表,请访问Microsoft的 C# 文档。
示例
以下示例演示使用StreamWriter类将文本数据写入文件:
using System;
using System.IO;
namespace FileApplication
{
   class Program
   {
      static void Main(string[] args)
      {
         string[] names = new string[] {"Max Su", "Sukida"};
         using (StreamWriter sw = new StreamWriter("all_names.txt"))
         {
            foreach (string s in names)
            {
               sw.WriteLine(s);
            }
         }
         // Read and show each line from the file.
         string line = "";
         using (StreamReader sr = new StreamReader("all_names.txt"))
         {
            while ((line = sr.ReadLine()) != null)
            {
               Console.WriteLine(line);
            }
         }
         Console.ReadKey();
      }
   }
}
当上述代码被编译并执行时,它产生以下结果:
Max Su
Sukida
