遍历文件夹,搜索文件中的文本

遍历设定好的文件夹下所有文件,及其下所有各级子目录的文件。

检索文本文件,并匹配输入的字符串。

支持区分大小写。

image

 

Regex m_RegTxt = null;
// 搜索按钮执行
    private void btnSearch_Click(object sender, EventArgs e)
{
listViewSearch.Items.Clear();
if ((txtDir.Text.Length < 1) || (txtToSearch.Text.Length < 1))
{
MessageBox.Show("Set parameters before search!", "Remind", MessageBoxButtons.OK, MessageBoxIcon.Information);
return;
}
if(cboxCase.Checked)
m_RegTxt = new Regex(txtToSearch.Text, RegexOptions.Singleline);
else
m_RegTxt = new Regex(txtToSearch.Text, RegexOptions.Singleline|RegexOptions.IgnoreCase);
m_RootDir = txtDir.Text;
try
{
SearchDir(txtDir.Text);
}
catch (Exception exp)
{
MessageBox.Show(exp.Message, "Exception Found", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
lblStatus.Text = "Status: Search end.";
}
// 搜索指定文件夹,并递归搜索其子文件夹
    private void SearchDir(string dir)
{
lblStatus.Text = "Search DIR: " + dir;
string[] arrFolders = new string[0];
string[] arrFiles = new string[0];
try
{
arrFolders = Directory.GetDirectories(dir);
arrFiles = Directory.GetFiles(dir);
}
catch
{
MessageBox.Show("Please set the correct Directory Path", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
for(int i=0; i"Search DIR: " + dir;
// search the files
        for(int i=0; i// 搜索特定的文件
private void SearchFile(string file)
{
StreamReader srFile = File.OpenText(file);
string line = srFile.ReadLine();
int lineNo = 1;
string fileName = string.Empty;
int iIndex = 0;
iIndex = file.LastIndexOf('\\');
if(iIndex < 0)
iIndex = file.LastIndexOf('/');
if (iIndex < 0)
iIndex = 0;
fileName = file.Substring(iIndex);
Match match = null;
int iRootDirLen = m_RootDir.Length;
while (line != null)
{
// match
            match = m_RegTxt.Match(line);
if (match.Success)
{
// add to list
                ListViewItem lvItem = new ListViewItem(new string[] {
fileName,
lineNo.ToString() ,
line.Substring(match.Index, line.Length-match.Index>51?50:line.Length-match.Index),
file.Substring(iRootDirLen)
});
listViewSearch.Items.Add(lvItem);
}
line = srFile.ReadLine();
++lineNo;
}
srFile.Close();
srFile.Dispose();
srFile = null;
}
posted @ 2008-02-28 08:21  马建康  阅读(613)  评论(0)    收藏  举报