本文實例講述了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#程序設計有所幫助。
新聞熱點
疑難解答