下面的程序解析了一个所谓的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();
}
}
}
Run Code Online (Sandbox Code Playgroud)
您可以使用它Directory.EnumerateFiles来获取目录中的所有文件并循环遍历它们.您可以提供搜索规范以及搜索是否应该是递归的,具体取决于您使用的参数和重载.
顺便说一句 - 您应该将您的流包装在using语句中以确保正确处理:
using(TextReader tr = new StreamReader(filePath))
{
using(TextWriter tw = new StreamWriter(destPath))
{
....
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3504 次 |
| 最近记录: |