아래의 프로그램은 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();
}
}
}
* 사용하면 *. * 내게 표시되지 않습니다. –
@Raven Dreamer - 코드를 사용하면'Close'가 호출되기 전에 예외가 발생하면 스트림이 닫히지 않습니다. – Oded
아, 마지막으로 마침내 닫을 수도 있습니다. 잡았다. –