C# 使用Shell(DIR)快速列出目录
我正在做一些工作来优化在网络驱动器中以C#、文件和文件夹的形式列出文件夹的内容。对于文件,我需要文件名、文件大小和修改日期,对于文件夹,只需要名称和修改日期 我在StackOverflow上搜索了各种解决方案,并决定使用Directory.GetFiles,使用EnumerateFiles没有任何好处,因为我没有并行处理这些文件 我的测试用例在WAN上有4000个和5个子文件夹,GetFiles仍然需要30秒或更长时间,而Windows可以在2秒钟内对文件夹进行定向 我不想涉及太多的windowsapi代码,所以我认为一个好的折衷办法是抛出DIR命令,重定向标准输出并解析输入。不漂亮,但应该没问题。我发现这段代码几乎满足了我的要求:C# 使用Shell(DIR)快速列出目录,c#,directory,createprocess,processstartinfo,C#,Directory,Createprocess,Processstartinfo,我正在做一些工作来优化在网络驱动器中以C#、文件和文件夹的形式列出文件夹的内容。对于文件,我需要文件名、文件大小和修改日期,对于文件夹,只需要名称和修改日期 我在StackOverflow上搜索了各种解决方案,并决定使用Directory.GetFiles,使用EnumerateFiles没有任何好处,因为我没有并行处理这些文件 我的测试用例在WAN上有4000个和5个子文件夹,GetFiles仍然需要30秒或更长时间,而Windows可以在2秒钟内对文件夹进行定向 我不想涉及太多的window
Process process = new Process();
process.StartInfo.FileName = "ipconfig.exe";
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
process.Start();
// Synchronously read the standard output of the spawned process.
StreamReader reader = process.StandardOutput;
string output = reader.ReadToEnd();
这对ipconfig.exe很好,但是DIR不是一个exe,所以我怎么称呼它呢?我想重定向如下内容:
目录“\MyNasDrive\MyFolder”
最糟糕的情况是,我可以将其封装在一个.bat文件中,但这感觉相当糟糕
任何想法都值得赞赏
==找到了我自己的解决方案,但如果您发现有任何问题,请告诉我==
string DirPath = "\\\\MYServer\\MyShare\\";
Process process = new Process();
process.StartInfo.FileName = "C:\\Windows\\System32\\cmd.exe";
process.StartInfo.Arguments = "/C DIR /-C \"" + DirPath + "\"";
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
process.StartInfo.CreateNoWindow = true;
process.Start();
// Synchronously read the standard output of the spawned process. Note we aren't reading the standard err, as reading both
// Syncronously can cause deadlocks. https://msdn.microsoft.com/en-us/library/system.diagnostics.processstartinfo.redirectstandardoutput(v=vs.110).aspx
//if we need to do this in the future then might be able to use https://msdn.microsoft.com/en-us/library/system.diagnostics.process.beginoutputreadline(v=vs.110).aspx
StreamReader reader = process.StandardOutput;
string output = reader.ReadToEnd();
process.WaitForExit();
process.Close();
DIR不是一个exe
cmd.exe
是一个exe
使用两个参数调用cmd.exe
:
/C
dir
注意:您也可以将UseShellExecute设置为true。
使用EnumerateFile没有任何好处
当您使用EnumerateFiles
而不是GetFiles
时,代码花费了多长时间?使用EnumerateFile时,代码以相同的速度运行,因为在EnumerateFile调用之后,我需要一个循环来读取所有文件价值观。我的代码在没有读取所有值的情况下无法继续,因此我认为没有任何速度优势。显然,如果我加载文件,那么我可以并行化,但我只是读取文件名、大小和修改日期。