C# FileStream StreamWrite追加到文本文件末尾


該樣例為追加 C盤中的 file1.txt 的文本內容

完整代碼例如以下:

引入命名空間:

 

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

 

 

完整代碼:

 

[csharp]  view plain copy print ?
 
  1. namespace FileStreamWrite  
  2. {  
  3.     class Program  
  4.     {  
  5.         static void Main(string[] args)  
  6.         {  
  7.             FileStream fs = null;  
  8.             string filePath = "C:\\file1.txt";  
  9.             //將待寫的入數據從字符串轉換為字節數組  
  10.             Encoding encoder = Encoding.UTF8;  
  11.             byte[] bytes = encoder.GetBytes("Hello World! \n\r");  
  12.             try  
  13.             {  
  14.                 fs = File.OpenWrite(filePath);  
  15.                 //設定書寫的開始位置為文件的末尾  
  16.                 fs.Position = fs.Length;  
  17.                 //將待寫入內容追加到文件末尾  
  18.                 fs.Write(bytes, 0, bytes.Length);  
  19.             }  
  20.             catch (Exception ex)  
  21.             {  
  22.                 Console.WriteLine("文件打開失敗{0}", ex.ToString());  
  23.             }  
  24.             finally  
  25.             {  
  26.                 fs.Close();  
  27.             }  
  28.             Console.ReadLine();  
  29.         }  
  30.     }  
  31. }  

 

 

以上為完整代碼!

 

代碼中

[csharp]  view plain copy print ?
 
  1. fs = File.OpenWrite(filePath);  
  2. //設定書寫的開始位置為文件的末尾  
  3. fs.Position = fs.Length;  

等價於

 

 

[csharp]  view plain copy print ?
 
  1. fs = File.Open(filePath, FileMode.Append, FileAccess.ReadWrite);  

 

 

執行。。。沒效果如,呵呵,直接追加進去了,點擊文本就可以看到效果了。

 

若以上代碼編譯有問題,可下載項目文件直接編譯: http://download.csdn.net/source/3465946


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM