C#使用dir命令實(shí)現(xiàn)文件搜索功能示例
本文實(shí)例講述了C#使用dir命令實(shí)現(xiàn)文件搜索功能。分享給大家供大家參考,具體如下:
以往,我都是使用 System.IO.Directory.GetDirectories() 和 System.IO.Directory.GetFiles() 方法遍歷目錄搜索文件。但實(shí)際的執(zhí)行效果始終差強(qiáng)人意,在檢索多種類型文件方面不夠強(qiáng)大,尤其是在檢索特殊文件夾或遇到權(quán)限不足時(shí)會(huì)引發(fā)程序異常。
這次為朋友寫了個(gè)檢索圖片的小程序,在仔細(xì)研究了 Process 以及 ProcessStartInfo 之后,決定利用這兩個(gè)類以及系統(tǒng)命令 dir 對(duì)文件進(jìn)行檢索。
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);
// 如果僅搜索文件夾可以使用下面的參數(shù)組合
// 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) =>
{
// 根據(jù) p.Data 是否為空判斷 dir 命令是否已執(zhí)行完畢
if (string.IsNullOrEmpty(p.Data) == false)
{
output.AppendLine(p.Data);
// 可以寫個(gè)自定義類 <T>
// 然后利用 static <T> FromFile(string path) 的方式進(jìn)行實(shí)例化
// 最后利用 List<T>.Add 的方法將其加入到 List 中以便后續(xù)處理
// * 數(shù)據(jù)量很大時(shí)慎用
}
else
{
// 運(yùn)行到此處則表示 dir 已執(zhí)行完畢
// 可以在此處添加對(duì) output 的處理過(guò)程
// 也可以自定義完成事件并在此處觸發(fā)該事件,
// 將 output 作為事件參數(shù)進(jìn)行傳遞以便外部程序調(diào)用
}
};
compiler.Start();
compiler.BeginOutputReadLine(); // 開始異步讀取
compiler.Close();
}
}
更多關(guān)于C#相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《C#文件操作常用技巧匯總》、《C#遍歷算法與技巧總結(jié)》、《C#程序設(shè)計(jì)之線程使用技巧總結(jié)》、《C#常見控件用法教程》、《WinForm控件用法總結(jié)》、《C#數(shù)據(jù)結(jié)構(gòu)與算法教程》及《C#面向?qū)ο蟪绦蛟O(shè)計(jì)入門教程》
希望本文所述對(duì)大家C#程序設(shè)計(jì)有所幫助。
相關(guān)文章
c#高效率導(dǎo)出多維表頭excel的實(shí)例代碼
這篇文章介紹了c#高效率導(dǎo)出多維表頭excel的實(shí)例代碼,有需要的朋友可以參考一下2013-11-11

