我正在尝试使用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();
最佳答案
为什么不使用DirectoryInfo.GetFiles
?
我猜测您现在有相当多的时间被执行命令而不是.NET代码所占用。 dir
需要很长时间才能将这么多数据依次写入流中。然后,您使用String.Split
也会阻塞那么多数据。
通过使用DirectoryInfo.GetFiles,您应该能够在一行中获得所有文件名(并且您还可以通过这种方式获得有关文件的其他信息):
var files = (new DirectoryInfo(path)
.GetFiles("*.*", SearchOption.AllDirectories)
.Select(fi => fi.Name);
如果您真的只关心文件名,则可以使用:
var fileNames = Directory.GetFiles(path, "*.*", SearchOption.AllDirectories);
关于c# - C#-当数据约为400 MB时如何处理Process.StandardOutput中的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7570519/