StreamReader和StreamWriter类
在处理文本文件时,可能也希望使用StreamReader和StreamWriter类,StreamReader派生于TextReader类,TextReader类表示可以读取一系列顺序字符的读取器的抽象类。
下面代码使用StreamReader类读取文本文件中的多行文本:
- using System;
- using System.IO;
- class Test
- {
- public static void Main()
- {
- try
- {
- // Create an instance of StreamReader to read from a file.
- // The using statement also closes the StreamReader.
- using (StreamReader sr = new StreamReader("TestFile.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);
- }
- }
- }
除了ReadLine()方法之外,StreamReader类也支持如下的方法:
- Read():读取输入流中的下一个字符
- ReadBlock():读取最大数量的指定字符
- ReadToEnd():读取从当前位置到流末尾之间的字符
StreamWriter类派生于TextWriter抽象类,用于将字符写入流。下面的代码使用StreamWrirter类将多行文本写入文本文件:
- using System;
- using System.IO;
- namespace ConsoleApplicationStreamWriter
- {
- class Program
- {
- static void Main(string[] args)
- {
- // Get the directories currently on the C drive.
- DirectoryInfo[] cDirs = new DirectoryInfo(@"c:/").GetDirectories();
- // Write each directory name to a file.
- using (StreamWriter sw = new StreamWriter("CDriveDirs.txt"))
- {
- foreach (DirectoryInfo dir in cDirs)
- {
- sw.WriteLine(dir.Name);
- }
- }
- // Read and show each line from the file.
- string line = "";
- using (StreamReader sr = new StreamReader("CDriveDirs.txt"))
- {
- while ((line = sr.ReadLine()) != null)
- {
- Console.WriteLine(line);
- }
- }
- Console.ReadLine();
- }
- }
- }