c# - 重命名目录树C#中的每个文件
问题描述
我有一个目录树,想重命名每个文件和子目录。在每个目录中,文件和子目录都需要重命名为从 1 开始的数字。例子:
原始目录树:
Root
- Cooldir
- anotherdir
- file.txt
- file.png
- Randomdir
- secondfile.png
- name.txt
我希望它看起来像什么。
Root
- 1
- 1
- 1
- 2
- 2
- 1
- 3
解决方案
一个简单的例子可能如下:
void Recursive(string path)
{
var exps = Enumerable
.Union(Directory.EnumerateFiles(path).Select(o => new ExplorerInfo
{
Path = Path.GetDirectoryName(o),
Name = Path.GetFileNameWithoutExtension(o),
Ext = Path.GetExtension(o),
IsDir = false
}), Directory.EnumerateDirectories(path).Select(o => new ExplorerInfo
{
Path = Path.GetDirectoryName(o),
Name = Path.GetFileName(o),
IsDir = true
})
.OrderBy(n => Path.GetFileName(n.Name)));
var i = 0;
foreach (var exp in exps)
{
if (exp.IsDir)
{
Recursive(exp.Path + "\\" + exp.Name);
Directory.Move(exp.Path + "\\" + exp.Name, exp.Path + $"/{++i}{exp.Ext}");
}
else
{
File.Move(exp.Path + "\\" + exp.Name + exp.Ext, exp.Path + $"/{++i}{exp.Ext}");
}
}
}
ExplorerInfo 类:
public class ExplorerInfo
{
public string Path { get; set; }
public string Name { get; set; }
public string Ext { get; set; }
public bool IsDir { get; set; }
}
下次,添加代码示例以使问题更清晰,并表明您确实尝试开发应用程序。
推荐阅读
- python - tensorflow(<2) 中有没有办法将动态输入形状与冻结图一起使用?
- go - 我们可以限制从 goroutine 一次调用一次函数吗
- ruby - 我正在尝试在我的 32 位 ubuntu 机器上安装自制软件。但它不工作,我得到了这个错误
- flutter - Flutter 中 DropDownMenu 按钮中的 OnTap 函数
- c# - C# 检索所有 SQL 查询结果
- docker - Docker 卷新手问题
- c# - Jetbrains Rider 中的启动项目选项
- github-actions - 如何安排 GitHub Actions 每晚构建,但仅在最近代码更改时才运行它?
- opc-ua - 节点的描述属性是否可以根据节点的值而改变?
- c++ - 为什么我的 OpenGL 上下文在此函数中为空,而在其他函数中不为空