试图想出一种方法来使用递归或linq来移动目录树,以获得具有以下形式的文件名:“C:\ Program Files(x86)\ Folder1 \ Folder2 \ TargetParentFolder \ TargetFolder \ TargetFolderName.ext“基本上,文件名将与文件夹名称完全相同,并且具有已知类型的文件扩展名,并且将位于TargetFolder目录中。然后我想打开“TargetFolderName.ext”文件,找到该文件中的特定字符串(字符串将始终在文件中)修改字符串,保存并关闭文件,将目录树移回TargetParentFolder获取下一个子文件夹并在下一个TargetFolder中重复对该文件的修改。到目前为止我所拥有的是:
FolderBrowserDialog folderPicker = new FolderBrowserDialog();
if (folderPicker.ShowDialog() == DialogResult.OK)
{
lsvAddons.Items.Clear();
List<string> folders = new List<string>(Directory.EnumerateDirectories(folderPicker.SelectedPath));
foreach (var folder in folders)
{
var folderName = Path.GetDirectoryName(Path.GetDirectoryName(folder));
var file = Directory.GetFiles(folderName, "*.toc", SearchOption.AllDirectories)
.FirstOrDefault();
ListViewItem item = new ListViewItem(folderName);
item.Tag = folder;
lsvAddons.Items.Add(item);
}
}
理想情况下,不会有ListView控件,而是一个集合,它将保存文件夹,并在填充集合后对每个匹配的文件名进行迭代修改。想法?
答案 0 :(得分:0)
我建议使用递归,如下所示:
void WalkDirectoryTree(System.IO.DirectoryInfo root)
{
System.IO.FileInfo[] files = null;
System.IO.DirectoryInfo[] subDirs = null;
try
{
files = root.GetFiles("*.*");
}
catch (UnauthorizedAccessException e)
{
}
catch (System.IO.DirectoryNotFoundException e)
{
}
if (files != null)
{
foreach (System.IO.FileInfo file in files)
{
if(file.Extension == ".ext"){
//open the file here, and make your modification
}
}
subDirs = root.GetDirectories();
foreach (System.IO.DirectoryInfo dirInfo in subDirs)
{
// Recursive call for each sub directory.
WalkDirectoryTree(dirInfo);
}
}
}
这将访问每个级别并检查文件,请查看此链接以获取MSDN
的完整示例:
https://msdn.microsoft.com/en-us/library/bb513869.aspx