现在的位置: 首页 > 综合 > 正文

[C#] 利用 dir 命令实现文件搜索

2014年01月09日 ⁄ 综合 ⁄ 共 1364字 ⁄ 字号 评论关闭

    以往,我都是使用 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();
    }
}

这是我随意写的一个方法,朋友们可以自己进行扩展或写成类。

需要注意的地方是: ProcessStartInfo 的 UseShellExecute 和 RedirectStandardOutput 属性。

另外,请仔细阅读 Process.BeginOutputReadLine 方法的备注信息。

抱歉!评论已关闭.