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進行處理也不太合适,也許應該用多線程來處理好一點.可是用多線程怎么做?
- C#做文件內容搜索
- C# 文件搜索
- C#文件搜索实例
- C#文件搜索实例
- C#文件搜索代码
- C# 搜索文件目录
- C#文件搜索
- c#做文件上传
- C#实现硬盘文件搜索
- C#文件搜索小程序
- c# 资源文件做背景音乐
- C#用集合做 多条件搜索功能
- C# 下获取搜索的文件
- C#读PPT文件与搜索
- 用Visual C#做DLL文件
- VS2008 C#用资源文件做背景音乐
- 关于IO流做的文件搜索器
- C# 封装磁盘目录文件搜索功能的工具类
- 我的第一个ACE测试例子(Linux和Windows)
- char
- static和final修饰类属性变量及初始化
- 面试题及答案 (JAVA)
- 链接服务器的配置和使用(SQL Server)
- C#做文件內容搜索
- 栈
- c#输出螺旋矩阵的一种拙解
- 3-OSWorkflow源码分析
- Cxgrid编辑后不能自动保存
- How to: Protect Against Script Exploits in a Web Application by Applying HTML Encoding to Strings
- 别了,理想的需求管理
- 最近学习(2.26)
- 链表