StreamWriter类的一般使用方法[转]

url: http://www.cnblogs.com/wxhpy7722/archive/2011/08/22/2149886.html

 理解StreamWriter可以对照StreamReader类来进行,因为他们只是读写的方式不同,一个是读,一个是写,其他的差别不是特别大。

    StreamWriter继承于抽象类TextWriter,是用来进行文本文件字符流写的类。

    它是按照一种特定的编码从字节流中写入字符,其常用的构造函数如下:

public StreamWriter (string path)//1
public StreamWriter (string path,bool append)//2
public StreamWriter (string path,bool append,Encoding encoding)//3

第1个构造函数,是以默认的形式进行,字符的编码依旧是UTF-8.

第2个构造函数,是1的具体话,引入了一个参数append,这个参数决定了当文件存在的时候,是覆盖还是追加,如果为false,则是覆盖,如果为true,则是追加,1的本质是publicStreamWriter (string path,false)

第三个构造函数是2的具体化,引入了具体的字符编码Encoding,默认的情况是UTF-8。

如果文件不存在,会自动创建文件。

 StreamWriter的两个重要的方法是Write()与WriteLine()。下面具体来说一说。

Write(string)方法是直接将string写入到文件中,而WriteLine(string)写完string加了一个回车换行,参见下面的代码的区别:

 1 Write
 2 
 3 using System;
 4 using System.IO;
 5 using System.Text;
 6 
 7 class Test
 8 {
 9 
10     public static void Main()
11     {
12         try
13         {
14             using (StreamWriter sw= new StreamWriter("TestFile.txt"))
15             {
16                 string str1 = "abc";
17                 string str2 = "def";
18                 sw.Write(str1);
19                 sw.Write(str2);
20             }
21         }
22         catch (Exception e)
23         {
24             Console.WriteLine("The file could not be read:");
25             Console.WriteLine(e.Message);
26         }
27     }
28 }
原文地址:https://www.cnblogs.com/xiexiaokui/p/2843350.html