让我们考虑一下,
E:/Folder2/Fol24/Fo2222
E:/Folder3/Fol23/Folder333
E:/Folder4/Folde25/Fold44
E:/Folder5/Folder55/Folde5
我需要使用E:/Folder?/Fol2?/Fo*
之类的输入来存档并从通配符匹配文件夹中删除所有文件
在这里,我期待文件夹E:/Folder2/Fol24/Fo2222
和E:/Folder3/Fol23/Folder333
这里的问题是用户可以输入任何通配符的模式。根据模式,我必须将文件复制到其他位置并删除文件。在这里,我无法使用任何固定的搜索模式。它应该是动态的,并且可以包含任意数量的通配符。
感谢您的帮助。
此致 钱德拉
答案 0 :(得分:0)
private static List<string> folders = new List<string>();
private void buttonExample_Click(object sender, EventArgs e)
{
folders.Clear();
string input = textBox1.Text;
string currentDir = string.Empty, currentPattern = string.Empty, nextPattern = string.Empty;
foreach (char c in input)
{
if (c == '?')
{
string[] f = input.Split(new[] {'?'}, 2);
if (f[0].Length > 0)
{
currentDir = Directory.GetParent(f[0]).FullName;
}
if (f[1].Length > 0)
{
nextPattern = f[1].TrimStart('\\');
}
string[] w = input.Split('\\');
foreach (string s in w)
{
if (s.Contains('?'))
{
currentPattern = s;
break;
}
}
break;
}
else if(c == '*')
{
string[] f = input.Split(new[] { '*' }, 2);
if (f[0].Length > 0)
{
currentDir = Directory.GetParent(f[0]).FullName;
}
if (f[1].Length > 0)
{
nextPattern = f[1].TrimStart('\\');
}
string[] w = input.Split('\\');
foreach (string s in w)
{
if (s.Contains('*'))
{
currentPattern = s;
break;
}
}
break;
}
}
DirectoryInfo di = new DirectoryInfo(currentDir);
List<string> foldersNew = new List<string>();
foldersNew = GetAllFolders(di, currentPattern, nextPattern);
}
private static List<string> GetAllFolders(DirectoryInfo currentDir,string currentPattern, string nextPatten)
{
DirectoryInfo[] dis = currentDir.GetDirectories(currentPattern);
if (dis.Length == 0 && string.Equals(currentPattern,string.Empty))
folders.Add(currentDir.FullName);
if (dis.Length > 0)
{
string[] remainPattern = nextPatten.Split("\\".ToCharArray());
if (remainPattern.Length > 0)
{
foreach (DirectoryInfo di in dis)
{
GetAllFolders(di, remainPattern.First(),
string.Join("\\", remainPattern.Skip(1).ToArray()));
}
}
}
return folders;
}
我的解决方案可能对有需要的人有所帮助。这将解决问题。感谢大家的帮助。