源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

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

  • 时间:2020-09-19 15:02 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要: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#相关内容感兴趣的读者可查看本站专题:《[url=http://www.1sucai.cn/Special/257.htm]C#文件操作常用技巧汇总[/url]》、《[url=http://www.1sucai.cn/Special/777.htm]C#遍历算法与技巧总结[/url]》、《[url=http://www.1sucai.cn/Special/227.htm]C#程序设计之线程使用技巧总结[/url]》、《[url=http://www.1sucai.cn/Special/165.htm]C#常见控件用法教程[/url]》、《[url=http://www.1sucai.cn/Special/125.htm]WinForm控件用法总结[/url]》、《[url=http://www.1sucai.cn/Special/116.htm]C#数据结构与算法教程[/url]》及《[url=http://www.1sucai.cn/Special/478.htm]C#面向对象程序设计入门教程[/url]》 希望本文所述对大家C#程序设计有所帮助。
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部