2017-03-03 88 views
0

所以我有這樣的代碼:如何將文本附加到C#中所有現有的.txt文檔?

class Program 
    { 

     static void Main(string[] args) 
     { 
      // Set a variable to the My Documents path. 
      string mydocpath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); 

      var dir = new DirectoryInfo(mydocpath + @"\sample\"); 
      string msg = "Created by: Johny"; 

      foreach (var file in dir.EnumerateFiles("*.txt")) 
      { 
       file.AppendText(msg); //getting error here 
      } 
     } 
    } 

而且我想頁腳添加到樣本文件夾中所有的文本文件,但由於AppendText通過不接受一個字符串參數,我得到一個錯誤。我只是想知道我該怎麼做?

回答

1

你想用從AppendText通過我認爲的StreamWriter:

 static void Main(string[] args) 
     { 
      // Set a variable to the My Documents path. 
      string mydocpath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); 

      var dir = new DirectoryInfo(mydocpath + @"\sample\"); 
      string msg = "Created by: Johny"; 

      foreach (var file in dir.EnumerateFiles("*.txt")) 
      { 
       var streamWriter = file.AppendText(); 
       streamWriter.Write(msg); 
       streamWriter.Close(); 
      } 
     } 
1

FileInfo.AppendText()創建一個StreamWriter,它不會附加文本本身。要做到這一點:

using (var sw = file.AppendText()) { 
    sw.Write(msg); 
} 
0

AppendText對於StreamWriter擴展方法,請參閱documentation

所以,你應該請寫下這些代碼:

foreach (var file in dir.EnumerateFiles("*.txt")) 
{ 
    using (StreamWriter sw = File.AppendText(file.FullName)) 
    { 
     sw.WriteLine(msg); 
    } 
} 
相關問題