C# - 当数据大约为400 MB时,如何从Process.StandardOutput处理数据

May*_*r J 1 c# shell optimization file-handling

我试图用Windows命令从服务器检索文件列表 - "DIR/S/B"输出很大(大约400 MB).现在,当我尝试使用以下方法检索它时,需要花费数小时来处理.有没有更快的方法来做到这一点.

string path = args[0];
var start = DateTime.Now;

System.Diagnostics.ProcessStartInfo procStartInfo =
    new System.Diagnostics.ProcessStartInfo("cmd", "/c " + "dir /s/b " + path );
procStartInfo.RedirectStandardOutput = true;
procStartInfo.UseShellExecute = false;
procStartInfo.CreateNoWindow = true;
System.Diagnostics.Process proc = new System.Diagnostics.Process();
proc.StartInfo = procStartInfo;
proc.Start();

//string [] result = proc.StandardOutput.ReadToEnd().Split('\n'); ;

StreamWriter writer = new StreamWriter("FileList.lst");
while (proc.StandardOutput.EndOfStream != true)
{
    writer.WriteLine(proc.StandardOutput.ReadLine());
    writer.Flush();
}
writer.Close();
Run Code Online (Sandbox Code Playgroud)

Jus*_*ner 7

为什么不用DirectoryInfo.GetFiles

我猜你现在的相当多的时间都被执行的命令所吞噬,而不是.NET代码.将dir这么多数据按顺序写入流中需要很长时间.然后你使用String.Split哪个也会扼杀这么多数据.

通过使用DirectoryInfo.GetFiles,您应该能够在一行中获取所有文件名(并且您还可以通过这种方式获取有关文件的其他信息):

var files = (new DirectoryInfo(path)
                .GetFiles("*.*", SearchOption.AllDirectories)
                .Select(fi => fi.Name);
Run Code Online (Sandbox Code Playgroud)

如果您真的只关心文件名,可以使用:

var fileNames = Directory.GetFiles(path, "*.*", SearchOption.AllDirectories);
Run Code Online (Sandbox Code Playgroud)