C# 使用 StreamWriter 写入数据

NetworkStream 类、MemoryStream类 和 FileStream 类都提供了以字节为基本单位的读写方法,但是这种方法首先将待写入的数据转换为字节序列后才能进行读写,当操作的是使用字符编码的文本数据时,使用很不方便。因此,在操作文本数据时,一般使用StreamWriter 类与 StreamReader 类执行这些功能。这是因为 Stream 类操作的是字节和字节数组,而 StreamWriter 类与 StreamReader 类自身对底层的转换进行了封装,使开发人员直接操作的就是字符数据,更易于使用。


下面是代码例子:


引入命名空间:

[csharp] view plain copy
 print?
  1. using System.IO;  

完整代码:

[csharp] view plain copy
 print?
  1. namespace StreamWriterApp  
  2. {  
  3.     class Program  
  4.     {  
  5.         static void Main(string[] args)  
  6.         {  
  7.             StreamWriter sw = null;  
  8.             string strPath = "C:\file1.txt";  
  9.             try  
  10.             {  
  11.                 sw = new StreamWriter(strPath);  
  12.                 sw.WriteLine("当前时间为:" + DateTime.Now);  
  13.                 Console.WriteLine("写文件成功!");  
  14.             }  
  15.             catch (Exception ex)  
  16.             {  
  17.                 Console.WriteLine("写文件失败:" + ex.Message);  
  18.             }  
  19.             finally  
  20.             {  
  21.                 if (sw != null)  
  22.                     sw.Close();  
  23.             }  
  24.             Console.ReadLine();  
  25.         }  
  26.     }  
  27. }  

运行效果。。。。。直接看C盘file1.txt就可以啦。


下面是我上传的已经成功编译的项目包:http://download.csdn.net/source/3466066

原文地址:https://www.cnblogs.com/alan666/p/8312192.html