好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

C#使用dir命令实现文件搜索功能示例

本文实例讲述了C#使用dir命令实现文件搜索功能。分享给大家供大家参考,具体如下:

以往,我都是使用 System.IO.Directory.GetDirectories() 和 System.IO.Directory.GetFiles() 方法遍历目录搜索文件。但实际的执行效果始终差强人意,在检索多种类型文件方面不够强大,尤其是在检索特殊文件夹或遇到权限不足时会引发程序异常。

这次为朋友写了个检索图片的小程序,在仔细研究了 Process 以及 ProcessStartInfo 之后,决定利用这两个类以及系统命令 dir 对文件进行检索。

?

private void search()

{

   // 多种后缀可使用 exts 定义的方式

   var ext = "*.jpg" ;

   var exts = "*.jpg *.png *.gif" ;

   var folder = "D:\\" ;

   var output = new StringBuilder();

   if (System.IO.Directory.Exists(folder))

   {

     string path = System.IO.Path.Combine(folder, exts);

     string args = string .Format( "/c dir \"{0}\" /b/l/s" , path);

     // 如果仅搜索文件夹可以使用下面的参数组合

     // string args = string.Format("/c dir \"{0}\" /ad-s-h/b/l/s", folder);

     var compiler = new System.Diagnostics.Process();

     compiler.StartInfo.FileName = "cmd.exe" ;

     compiler.StartInfo.Arguments = args;

     compiler.StartInfo.CreateNoWindow = true ;

     compiler.StartInfo.UseShellExecute = false ;

     compiler.StartInfo.RedirectStandardOutput = true ;

     compiler.OutputDataReceived += (obj, p) =>

     {

       // 根据 p.Data 是否为空判断 dir 命令是否已执行完毕

       if ( string .IsNullOrEmpty(p.Data) == false )

       {

         output.AppendLine(p.Data);

         // 可以写个自定义类 <T>

         // 然后利用 static <T> FromFile(string path) 的方式进行实例化

         // 最后利用 List<T>.Add 的方法将其加入到 List 中以便后续处理

         // * 数据量很大时慎用

       }

       else

       {

         // 运行到此处则表示 dir 已执行完毕

         // 可以在此处添加对 output 的处理过程

         // 也可以自定义完成事件并在此处触发该事件,

         // 将 output 作为事件参数进行传递以便外部程序调用

       }

     };

     compiler.Start();

     compiler.BeginOutputReadLine(); // 开始异步读取

     compiler.Close();

   }

}

希望本文所述对大家C#程序设计有所帮助。

dy("nrwz");

查看更多关于C#使用dir命令实现文件搜索功能示例的详细内容...

  阅读:55次