下面的程序解析了一个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();
}
}
}
*使用*让我那.Close()不? – 2011-03-24 22:44:30
@Raven Dreamer - 使用你的代码时,如果在调用Close之前引发异常,流将不会被关闭。 – Oded 2011-03-24 22:45:32
啊,所以我也可以在最后关闭它们。疑难杂症。 – 2011-03-24 22:47:39