【问题标题】:Rename every file in directory tree C#重命名目录树C#中的每个文件
【发布时间】:2021-09-28 17:26:24
【问题描述】:

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

原始目录树:

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

我希望它看起来像什么。

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

【问题讨论】:

  • 您能分享一些您尝试过的代码以及遇到的问题吗?

标签: c# .net-core directory


【解决方案1】:

一个简单的例子如下:

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

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

【讨论】:

    猜你喜欢
    • 2012-01-27
    • 2022-07-21
    • 2011-12-29
    • 2013-02-12
    • 2021-03-28
    • 2014-10-09
    • 2014-08-21
    • 2018-06-27
    • 2012-12-27
    相关资源
    最近更新 更多