C#做文件內容搜索

来源:互联网 发布:js怎么禁止点击事件 编辑:程序博客网 时间:2024/04/24 04:26

C#文件內容搜索

1.檢索指定文件中是否含有指定字符串
        /// <summary>
        /// 檢索指定文件中是否含有指定字符串
        /// </summary>
        /// <param name="strSearch">匹配字符串</param>
        /// <param name="fileName">文件完整名稱</param>
        /// <returns>若含有指定字符串,則返回true</returns>
        public bool SearchFile(string strSearch, string fileName)
        {
            bool result = false;
            StreamReader sr = new StreamReader(fileName, System.Text.Encoding.Default);
            string strLine;
            while ((strLine = sr.ReadLine()) != null)
            {
                if (strLine.IndexOf(strSearch) != -1)
                {
                    result = true;
                    break;
                }
            }
            sr.Close();

            return result;
        }

2.遞歸調用
        /// <summary>
        /// 搜索指定目錄中的文件
        /// </summary>
        /// <param name="strSearch">匹配字符串</param>
        /// <param name="strDir">欲檢索的目錄</param>
        /// <param name="strExp">文件后綴名(不含點號)</param>
        /// <param name="tree">是否檢索子目錄</param>
        public void SearchFiles(string strSearch,string strDir, string strExp, bool tree)
        {
            DirectoryInfo dir = new DirectoryInfo(strDir);
            FileInfo[] filelist = dir.GetFiles("*." + strExp);
            for (int i = 0; i < filelist.Length; i++)
            {
  //開始檢索一個文件時的代碼
  //BeginSearch(filelist[i].FullName);
                if (SearchFile(strSearch, filelist[i].FullName))
                {
                    //檢索到一個匹配文件的代碼
      //Searching(filelist[i].FullName); 
                }
            }
            if (tree)
            {
                DirectoryInfo[] dir1 = dir.GetDirectories();
                for (int j = 0; j < dir1.Length; j++)
                {
                    SearchFiles(strSearch,dir1[j].FullName.Replace("/","//"), strExp, tree);
                }
            }
     //檢索整個目錄完成后的代碼
     //EndSearch(strDir);
           
        }

3.最終實現
                this.richTextBox1.Text = "";//用于顯示檢索到的文件名稱
                string strDir = this.textBox1.Text.Replace("/","//");
                string strExp = this.textBox2.Text;
                string strSearch = this.textBox3.Text;
                bool tree = this.checkBox1.Checked;
  SearchFiles(strSearch, strDir, strExp, tree);

private void BeginSearch(string strDirName)
{
     //this.label4.Text = filelist[i].FullName.ToString().Replace("/", "//");
     //this.label4.Refresh();
}
private void Searching(string strFileName)
{
     // this.richTextBox1.AppendText(filelist[i].FullName.Replace("/", "//") + "/r/n");
}
private void EndSearch(string strDirName)
{
     //this.label4.Text = "搜索完畢";
}


總結:在檢索時好像好挂起界面,但像這种情況,好像用BackgroundWorker進行處理也不太合适,也許應該用多線程來處理好一點.可是用多線程怎么做?
 

原创粉丝点击