private void btnSearch_Click(object sender, EventArgs e)
{
string[] patterns = { @"/w*/.*" };
string path = txtSource.Text;
DisplayFileInfo(@C:/logs, patterns, true);
}
private void DisplayFileInfo(string path, string[] filePatterns, bool includeSubDirs)
{
string[] items = GetFiles(path);
if (items.Length != 0)
foreach (string item in items)
if (filePatterns.Length != 0)
{
foreach (string pattern in filePatterns)
{
if (Regex.IsMatch(item, pattern))
{
DisplayTitleAndContent(item);
break;
}
}
}
else
{
DisplayTitleAndContent(item);
}
if (includeSubDirs)
{
items = GetDirs(path);
if (items.Length != 0)
foreach (string item in items)
DisplayFileInfo(item, filePatterns, true);
}
}
private void DisplayTitleAndContent(string path)
{
string delim = new string('-', 20);
try
{
using (StreamReader streamReader = new StreamReader(path))
{
Console.WriteLine(delim);
Console.WriteLine("File Path: " + path);
Console.WriteLine("/n Content: /n");
while (!streamReader.EndOfStream)
Console.WriteLine(streamReader.ReadLine() + delim + "/n/n/n");
Console.WriteLine(delim + "/n/n/n");
}
}
catch (System.IO.IOException e)
{
Console.WriteLine(e.Message);
}
}
static string[] GetDirs(string path)
{
string[] dirs = Directory.GetDirectories(path);
return dirs;
}
static string[] GetFiles(string path)
{
string[] files = Directory.GetFiles(path);
return files;
}
}
本文介绍了一个基于C#的文件搜索程序,该程序可以根据指定的正则表达式模式搜索目录及子目录下的文件,并显示文件路径及内容。文章通过具体代码展示了如何使用Directory类获取目录信息,如何使用Regex类匹配文件名,以及如何读取并输出文件内容。

1430

被折叠的 条评论
为什么被折叠?



