StreamReader和StreamWriter类

 StreamReader和StreamWriter类 

在处理文本文件时,可能也希望使用StreamReader和StreamWriter类,StreamReader派生于TextReader类,TextReader类表示可以读取一系列顺序字符的读取器的抽象类。

下面代码使用StreamReader类读取文本文件中的多行文本:

 

  1. using System;  
  2. using System.IO;  
  3.   
  4. class Test   
  5. {  
  6.     public static void Main()   
  7.     {  
  8.         try   
  9.         {  
  10.             // Create an instance of StreamReader to read from a file.  
  11.             // The using statement also closes the StreamReader.  
  12.             using (StreamReader sr = new StreamReader("TestFile.txt"))   
  13.             {  
  14.                 string line;  
  15.                 // Read and display lines from the file until the end of   
  16.                 // the file is reached.  
  17.                 while ((line = sr.ReadLine()) != null)   
  18.                 {  
  19.                     Console.WriteLine(line);  
  20.                 }  
  21.             }  
  22.         }  
  23.         catch (Exception e)   
  24.         {  
  25.             // Let the user know what went wrong.  
  26.             Console.WriteLine("The file could not be read:");  
  27.             Console.WriteLine(e.Message);  
  28.         }  
  29.     }  
  30. }  

 

除了ReadLine()方法之外,StreamReader类也支持如下的方法:

  • Read():读取输入流中的下一个字符
  • ReadBlock():读取最大数量的指定字符
  • ReadToEnd():读取从当前位置到流末尾之间的字符

StreamWriter类派生于TextWriter抽象类,用于将字符写入流。下面的代码使用StreamWrirter类将多行文本写入文本文件:

 

  1. using System;  
  2. using System.IO;  
  3.   
  4. namespace ConsoleApplicationStreamWriter  
  5. {  
  6.     class Program  
  7.     {  
  8.         static void Main(string[] args)  
  9.         {  
  10.             // Get the directories currently on the C drive.  
  11.             DirectoryInfo[] cDirs = new DirectoryInfo(@"c:/").GetDirectories();  
  12.   
  13.             // Write each directory name to a file.  
  14.             using (StreamWriter sw = new StreamWriter("CDriveDirs.txt"))  
  15.             {  
  16.                 foreach (DirectoryInfo dir in cDirs)  
  17.                 {  
  18.                     sw.WriteLine(dir.Name);  
  19.   
  20.                 }  
  21.             }  
  22.   
  23.             // Read and show each line from the file.  
  24.             string line = "";  
  25.             using (StreamReader sr = new StreamReader("CDriveDirs.txt"))  
  26.             {  
  27.                 while ((line = sr.ReadLine()) != null)  
  28.                 {  
  29.                     Console.WriteLine(line);  
  30.                 }  
  31.             }  
  32.             Console.ReadLine();  
  33.         }  
  34.     }  
  35. }  

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值