递规篇历路径之 使用正则过滤( 将符合正则的名称用另种正则格式替换掉 )某个路径下的所有文件或文件夹的完整路径
private void btn_open_Click(object sender, EventArgs e)
{
if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
{
tbox_way.Text = folderBrowserDialog1.SelectedPath;
}
}
#region
/// <summary>
/// 使用递归 篇历目录下的所有文件或文件夹
/// </summary>
/// <param name="fsinfo">FileSystemInfo数组参数</param>
/// <param name="swt">StreamWriter写入流对像</param>
public void Gets(FileSystemInfo[] fsinfo,StreamWriter swt)
{
foreach (FileSystemInfo s in fsinfo)
{
if (s is DirectoryInfo)
{
DirectoryInfo drc = new DirectoryInfo(s.FullName);
int i = drc.GetDirectories().Count() + drc.GetFiles().Count();
if (Regex.IsMatch(drc.FullName, tbox_first.Text)) //检查目录文件夹路径是否符合正则
{
Regex r = new Regex(tbox_first.Text);
string str = r.Replace(drc.FullName, tbox_new.Text); //使用正则替换符合表达式的目录
swt.WriteLine("文件夹名:" + str + " " + "子目录数:" + i.ToString() + " ");
}
else
{
swt.WriteLine("文件夹名:" + drc.FullName + " " + "子目录数:" + i.ToString() + " ");
}
FileSystemInfo[] fsnext = drc.GetFileSystemInfos();
Gets(fsnext, swt); //递规调用
}
else
{
FileInfo finfo = new FileInfo(s.FullName);
if (Regex.IsMatch(finfo.FullName, tbox_first.Text)) //检查目录文件路径是否符合正则
{
Regex r = new Regex(tbox_first.Text);
string str = r.Replace(finfo.FullName, tbox_new.Text); //使用正则替换符合表达式的目录
swt.WriteLine("文件名:" + str + " " + "子目录数: 0" + " " + "大小: " + finfo.Length);
}
else
{
swt.WriteLine("文件名:" + finfo.FullName+ " " + "子目录数: 0" + " " + "大小: " + finfo.Length);
}
}
}
}
#endregion
private void btn_go_Click(object sender, EventArgs e)
{
saveFileDialog1.Filter = "*.txt(文本文件)|*.txt";
if (tbox_way.Text != "" && tbox_first.Text != "" && tbox_new.Text != "")
{
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
DirectoryInfo dic = new DirectoryInfo(tbox_way.Text);
FileSystemInfo[] fsinfo = dic.GetFileSystemInfos();
StreamWriter swt = new StreamWriter(saveFileDialog1.FileName);
Gets(fsinfo, swt); //调用递规方法
swt.Close();
}
}
else
{
MessageBox.Show("输入不能为空!!");
}
}