2011-03-24 5 views
1

아래의 프로그램은 Dwarf Fortress.이라는 소위 RAW 파일 중 하나를 구문 분석합니다. 코드는 제대로 작동하지만 현재 구현에서는 각 파일에 대해 한 번씩 프로그램을 실행하고 매번 소스 파일을 수동으로 변경해야합니다. 어딘가에 주어진 폴더의 모든 텍스트 파일을 대신 구문 분석 할 수 있습니까?주어진 폴더의 모든 파일을 읽으려면 어떻게해야합니까?

(현재 출력 파일은 입력 파일과 동일한 폴더에 있음을 유의하십시오. 프로그램이 작성 중에 파일을 열려고하면 어떻게 될지 잘 모르겠지만 마음에 품는 무엇인가).

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

namespace ConsoleApplication1 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      // create reader & open file 
      string filePath = @"C:\foo\Dwarf Fortess\creature_domestic.txt"; 
      string destPath = @"C:\foo\Dwarf Fortess\eggCreatures.txt"; 
      string line; 
      // 
      TextReader tr = new StreamReader(filePath); 
      TextWriter tw = new StreamWriter(destPath); 

      // read a line of text 
      while ((line = tr.ReadLine()) != null) 
      { 

         if (line.Contains("[CREATURE:")) 
         { 
          tw.WriteLine(line); 
         } 
         if(line.Contains("[LAYS_EGGS]")) 
         { 
          tr.ReadLine(); 
          tr.ReadLine(); 
          tr.ReadLine(); 
          tw.WriteLine(tr.ReadLine()); 
          tw.WriteLine(tr.ReadLine()); 
         } 


      } 

      // close the stream 
      tr.Close(); 
      tw.Close(); 
     } 
    } 
} 

답변

5

Directory.EnumerateFiles을 사용하면 디렉토리 내의 모든 파일을 가져 와서 반복 할 수 있습니다. 사용중인 매개 변수와 과부하에 따라 검색 사양과 검색이 재귀해야하는지 여부를 지정할 수 있습니다. 닷넷의

using(TextReader tr = new StreamReader(filePath)) 
{ 
    using(TextWriter tw = new StreamWriter(destPath)) 
    { 
    .... 
    } 
} 
+0

* 사용하면 *. * 내게 표시되지 않습니다. –

+0

@Raven Dreamer - 코드를 사용하면'Close'가 호출되기 전에 예외가 발생하면 스트림이 닫히지 않습니다. – Oded

+0

아, 마지막으로 마침내 닫을 수도 있습니다. 잡았다. –

2

확인 Directory.EnumerateFiles 디렉토리의 모든 파일을 나열합니다. 옵션 매개 변수를 사용하여 재귀 적으로 작동하는지 여부를 선택할 수 있습니다.

그런 다음 하나씩 파일을로드하십시오.

1

어떤 버전 : -

은 BTW 당신은 ​​적절한 처분을 보장하기 위해 using 문에 스트림을 배치해야 하는가? Directory.GetFiles에 대해 linq를 사용하여 작성중인 파일을 제외 할 수 있습니다. 나는 지금 VS가 없어, 거기에 약간의 오류가있을 수 있지만 당신은 잘하면 아이디어를 얻을.

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

namespace ConsoleApplication1 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      string destPath = @"C:\foo\Dwarf Fortess\eggCreatures.txt"; 
      FileInfo fiDest = new FileInfo(destPath); 
      DirectoryInfo diDF = new DirectoryInfo(@"C:\foo\Dwarf Fortress"); 

      var files = from FileInfo f in diDF.GetFiles("*.txt") 
       where f.Name != fiDest.Name 
       select f 
      foreach(FileInfo fiRead in files) 
      { 

      // create reader & open file 
       string filePath = @"C:\foo\Dwarf Fortess\creature_domestic.txt"; 
       string line; 
       // 
       TextReader tr = fiRead.OpenText(); 
       TextWriter tw = new StreamWriter(destPath); 

       // read a line of text 
       while ((line = tr.ReadLine()) != null) 
       { 

          if (line.Contains("[CREATURE:")) 
          { 
           tw.WriteLine(line); 
          } 
          if(line.Contains("[LAYS_EGGS]")) 
          { 
           tr.ReadLine(); 
           tr.ReadLine(); 
           tr.ReadLine(); 
           tw.WriteLine(tr.ReadLine()); 
           tw.WriteLine(tr.ReadLine()); 
          } 


       } 

       // close the stream 
       tr.Close(); 
       tw.Close(); 
      } 
     } 
    } 
} 
관련 문제