目录

杂项构造(Miscellaneous constructs)

StreamReaderStreamWriter类用于读取和写入文本文件的数据。 这些类继承自抽象基类Stream,它支持将字节读写到文件流中。

StreamReader类

StreamReader类还继承自抽象基类TextReader,它表示用于读取一系列字符的阅读器。 下表描述了StreamReader类的一些常用methods -

Sr.No. 方法和描述
1

public override void Close()

它关闭StreamReader对象和底层流,并释放与读取器关联的所有系统资源。

2

public override int Peek()

返回下一个可用字符,但不使用它。

3

public override int Read()

从输入流中读取下一个字符,并将字符位置前移一个。

例子 (Example)

以下示例演示如何读取名为Jamaica.txt的文本文件。 该文件读取 -

Down the way where the nights are gay
And the sun shines daily on the mountain top
I took a trip on a sailing ship
And when I reached Jamaica
I made a stop

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,它可以编写一系列字符。

下表描述了此类最常用的方法 -

Sr.No. 方法和描述
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#文档。

例子 (Example)

以下示例演示如何使用StreamWriter类将文本数据写入文件 -

using System;
using System.IO;
namespace FileApplication {
   class Program {
      static void Main(string[] args) {
         string[] names = new string[] {"Zara Ali", "Nuha Ali"};
         using (StreamWriter sw = new StreamWriter("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("names.txt")) {
            while ((line = sr.ReadLine()) != null) {
               Console.WriteLine(line);
            }
         }
         Console.ReadKey();
      }
   }
}

编译并执行上述代码时,会产生以下结果 -

Zara Ali
Nuha Ali
↑回到顶部↑
WIKI教程 @2018