首页 > 解决方案 > 重命名目录树C#中的每个文件

问题描述

我有一个目录树,想重命名每个文件和子目录。在每个目录中,文件和子目录都需要重命名为从 1 开始的数字。例子:

原始目录树:

Root
- Cooldir
   - anotherdir
     - file.txt
   - file.png
- Randomdir
   - secondfile.png
- name.txt

我希望它看起来像什么。

Root
- 1
  - 1
    - 1
  - 2
- 2
  - 1
- 3

标签: c#.net-coredirectory

解决方案


一个简单的例子可能如下:

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; }
}

下次,添加代码示例以使问题更清晰,并表明您确实尝试开发应用程序。


推荐阅读