搜索文件或文件内容
public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/plain"; string strkey = context.Request["key"]; string path = context.Server.MapPath("~/news_html"); List<FileInfo> listJs = new List<FileInfo>(); if (!string.IsNullOrWhiteSpace(strkey)) { GetFiles(path, (FileInfo file) => { if (file.Extension.Equals(".html") && file.Name.Contains(strkey)) { listJs.Add(file); } }); } else { GetFiles(path, (FileInfo file) => { if (file.Extension.Equals(".html")) { listJs.Add(file); } }); } context.Response.Write(JsonConvert.SerializeObject(listJs)); } /// <summary> /// /// </summary> /// <param name="path"></param> /// <param name="fileRule"></param> public void GetFiles(string path, Action<FileInfo> fileRule) { Queue<string> queue = new Queue<string>(); queue.Enqueue(path); while (queue.Count > 0) { DirectoryInfo dirInfo = new DirectoryInfo(queue.Dequeue()); foreach (DirectoryInfo dirchildInfo in dirInfo.GetDirectories()) { queue.Enqueue(dirchildInfo.FullName); } foreach (FileInfo dirfileInfo in dirInfo.GetFiles()) { fileRule(dirfileInfo); } } } /// <summary> /// 从文件中找关键字 /// </summary> /// <param name="filename"></param> /// <param name="word"></param> public void FindInFile(string filename, string word) { System.IO.StreamReader sr = System.IO.File.OpenText(filename); string s = sr.ReadToEnd(); sr.Close(); string[] temp = s.Split('\n'); for (int i = 0; i < temp.Length; i++) { if (temp[i].IndexOf(word) != -1) { Console.WriteLine(string.Format( "Found in: {0}\n{1}\nLine: {2} \n", filename, temp[i].Trim(), i + 1)); } } } /// <summary> /// 从文件夹中找关键字 /// </summary> /// <param name="foldername"></param> /// <param name="word"></param> public void FindInDirectory(string foldername, string word) { System.IO.DirectoryInfo dif = new System.IO.DirectoryInfo(foldername); //遍历文件夹中的各子文件夹 foreach (System.IO.DirectoryInfo di in dif.GetDirectories()) { FindInDirectory(di.FullName, word); } //查询文件夹中的各个文件 foreach (System.IO.FileInfo f in dif.GetFiles()) { FindInFile(f.FullName, word); } } public bool IsReusable { get { return false; } }