C#多文本文件处理

Mic*_*eyn 1 c# visual-studio-2010 c#-4.0

假设您要编写一个处理多个文本文件的应用程序,在命令行中作为参数提供(例如,MyProcessor file1 file2 ...).这是一个非常常见的任务,经常使用Perl,但是如果想直接利用.NET并使用C#会怎样.

什么是最简单的C#4.0应用程序锅炉板代码,允许您这样做?它应该基本上包括逐行处理每个文件的每一行,并通过调用一个函数来处理它,或者可能有更好的方法来进行这种"组"行处理(例如,LINQ或其他一些方法).

Dar*_*rov 9

您可以通过读取每一行并将其传递给处理函数来并行处理文件:

class Program
{
    static void Main(string[] args)
    {
        Parallel.ForEach(args, file =>
        {
            using (var stream = File.OpenRead(file))
            using (var reader = new StreamReader(stream))
            {
                string line;
                while ((line = reader.ReadLine()) != null) 
                {
                    ProcessLine(line);
                }
            }
        });
    }

    static void ProcessLine(string line)
    {
        // TODO: process the line
    }
}
Run Code Online (Sandbox Code Playgroud)

现在只需致电: SomeApp.exe file1 file2 file3

这种方法的优点:

  • 并行处理文件=>利用多个CPU核心
  • 文件是逐行读取的,只有当前行保存在内存中,这样可以减少内存消耗,并允许您处理大文件