StreamWriter类的一般使用方法
?? ?理解StreamWriter可以對照StreamReader類來進行,因為他們只是讀寫的方式不同,一個是讀,一個是寫,其他的差別不是特別大。
??? StreamWriter繼承于抽象類TextWriter,是用來進行文本文件字符流寫的類。
??? 它是按照一種特定的編碼從字節流中寫入字符,其常用的構造函數如下:
public StreamWriter (string path)//1public StreamWriter (string path,bool append)//2
public StreamWriter (string path,bool append,Encoding encoding)//3
第1個構造函數,是以默認的形式進行,字符的編碼依舊是UTF-8.
第2個構造函數,是1的具體話,引入了一個參數append,這個參數決定了當文件存在的時候,是覆蓋還是追加,如果為false,則是覆蓋,如果為true,則是追加,1的本質是public StreamWriter (string path,false)
第三個構造函數是2的具體化,引入了具體的字符編碼Encoding,默認的情況是UTF-8。
如果文件不存在,會自動創建文件。
?
?StreamWriter的兩個重要的方法是Write()與WriteLine()。下面具體來說一說。
Write(string)方法是直接將string寫入到文件中,而WriteLine(string)寫完string加了一個回車換行,參見下面的代碼的區別:
Write using System;using System.IO;
using System.Text;
class Test
{
public static void Main()
{
try
{
using (StreamWriter sw= new StreamWriter("TestFile.txt"))
{
string str1 = "abc";
string str2 = "def";
sw.Write(str1);
sw.Write(str2);
}
}
catch (Exception e)
{
Console.WriteLine("The file could not be read:");
Console.WriteLine(e.Message);
}
}
} WriteLine using System;
using System.IO;
using System.Text;
class Test
{
public static void Main()
{
try
{
using (StreamWriter sw= new StreamWriter("TestFile.txt"))
{
string str1 = "abc";
string str2 = "def";
sw.WriteLine(str1);
sw.WriteLine(str2);
}
}
catch (Exception e)
{
Console.WriteLine("The file could not be read:");
Console.WriteLine(e.Message);
}
}
}
打開文件TestFile.txt就能找到它們的區別了。
轉載于:https://www.cnblogs.com/wxhpy7722/archive/2011/08/22/2149886.html
總結
以上是生活随笔為你收集整理的StreamWriter类的一般使用方法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Net C# 扩展方法
- 下一篇: Foreach语法