2009-10-13 72 views
0

我有* .mol擴展名的多個文件。在其中一些最後一行中有「M END」文本。我需要一個讀取所有這些文件的程序,在這些文件中搜索「M END」行,並將這個「M END」寫入文件末尾沒有「M END」行的文件中。 我寫了下面的C#代碼,但它不起作用。如何讀取含有文本行的某些文本,然後將此文本追加到缺少該文本行的多個文件的文本中?

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.IO; 


namespace ConsoleApplication6 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      foreach (string fileName in Directory.GetFiles("C:\\abc\\", "*.mol")) 
      { 

       System.IO.StreamReader file = new System.IO.StreamReader(fileName);      
       if ((file.ReadLine()) != ("M END")) 
       { 
        File.AppendAllText(fileName, "M END" + Environment.NewLine); 

       } 


      } 

     } 
    } 
} 

請幫幫我! 感謝您的所有答案。

回答

1

如果你的文件不是很大,你可以試試這個

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.IO; 


namespace ConsoleApplication6 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      foreach (string fileName in Directory.GetFiles("C:\\abc\\", "*.mol")) 
      { 
       bool shouldAddMEnd = false; 
       using (System.IO.StreamReader sw = new System.IO.StreamReader(fileName)) 
       { 
        shouldAddMEnd = !sw.ReadToEnd().EndsWith("M END");       
       } 
       if (shouldAddMEnd) 
        File.AppendAllText(fileName, "M END" + Environment.NewLine); 
      } 
     } 
    } 
} 
+0

我試過,但它仍然無法正常工作。在調試過程中出現與我的代碼中相同的錯誤: 「進程無法訪問文件'C:\ abc \ 2ap-15.mol',因爲它正在被另一個進程使用。」 它停在以下行上: 「File.AppendAllText(fileName,」M END「+ Environment.NewLine);」 – Alex 2009-10-13 10:01:02

+0

哦,是的,我沒有注意到,現在嘗試編輯代碼 – 2009-10-13 10:36:20

相關問題