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

+0

아, 그래, 나는 메모를 작성하지 않았다. 편집 된 코드를 지금 사용해 보자. –

관련 문제