当前位置: 移动技术网 > IT编程>开发语言>c# > C#使用dir命令实现文件搜索功能示例

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

2019年07月18日  | 移动技术网IT编程  | 我要评论

本文实例讲述了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#相关内容感兴趣的读者可查看本站专题:《c#文件操作常用技巧汇总》、《c#遍历算法与技巧总结》、《c#程序设计之线程使用技巧总结》、《c#常见控件用法教程》、《winform控件用法总结》、《c#数据结构与算法教程》及《c#面向对象程序设计入门教程

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

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网