2009-10-13 71 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

相关问题