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 }