該樣例為追加 C盤中的 file1.txt 的文本內容
完整代碼例如以下:
引入命名空間:
- using System.IO;
完整代碼:
- namespace FileStreamWrite
- {
- class Program
- {
- static void Main(string[] args)
- {
- FileStream fs = null;
- string filePath = "C:\\file1.txt";
- //將待寫的入數據從字符串轉換為字節數組
- Encoding encoder = Encoding.UTF8;
- byte[] bytes = encoder.GetBytes("Hello World! \n\r");
- try
- {
- fs = File.OpenWrite(filePath);
- //設定書寫的開始位置為文件的末尾
- fs.Position = fs.Length;
- //將待寫入內容追加到文件末尾
- fs.Write(bytes, 0, bytes.Length);
- }
- catch (Exception ex)
- {
- Console.WriteLine("文件打開失敗{0}", ex.ToString());
- }
- finally
- {
- fs.Close();
- }
- Console.ReadLine();
- }
- }
- }
以上為完整代碼!
代碼中
- fs = File.OpenWrite(filePath);
- //設定書寫的開始位置為文件的末尾
- fs.Position = fs.Length;
等價於
- fs = File.Open(filePath, FileMode.Append, FileAccess.ReadWrite);
執行。。。沒效果如,呵呵,直接追加進去了,點擊文本就可以看到效果了。
若以上代碼編譯有問題,可下載項目文件直接編譯: http://download.csdn.net/source/3465946