使用 c# 从字符串路径构建文件夹/文件树 [英] Build folder/files tree from string path with c#

查看:68
本文介绍了使用 c# 从字符串路径构建文件夹/文件树的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要解决一个涉及从搅拌路径构建树的问题,以下是模型:

I need to solve a problem that involves building tree from stirng paths, here are the models:

public class Folder
{
    public string Name { get; set; }
    
    public List<Folder> Folders { get; set; } = new List<Folder>();
    public List<File> Files { get; set; } = new List<File>();
}

public class File 
{
    public string Name { get; set; }
}

这里是字符串路径:

var cars = new List<string>()
{
    "Car/",
    "Car/BMW/",
    "Car/Great Wall/",
    "Car/Great Wall/Another/",
    "Car/Great Wall/Another/test - file.bak",
    "Car/Great Wall/Another/second - file.bak",
    "Car/Great Wall/Car/",
    "Car/Great Wall/local - copy.bak",
    "Car/Great Wall/local - copy(2).bak",
    "Car/Mercedes/process - file.bak",
    "Car/Mercedes/process - file(2).bak",
    "Car/test123 - file.bak"
};

因此,我应该得到一个具有树结构的文件夹和文件列表,并且在显示时必须是这样的:

As a result I should get a List of Folders and Files with tree structure and when displaying it has to be something like this:

-Car
  -BMW
  -Great Wall
    -Another
      -test - file.bak
      -second - file.bak
    -Car
  -local - copy.bak
  -local - copy(2).bak
  -Mercedes
    -process - file.bak
    -process - file(2).bak
  -test123 - file.bak

非常感谢任何帮助:)

推荐答案

这里有代码:

using System;
using System.Collections.Generic;

namespace FolderTree
{
    public class Folder
    {
        public string Name { get; set; }
        public List<Folder> Folders { get; set; } = new List<Folder>();
        public List<File> Files { get; set; } = new List<File>();
    }

    public class File
    {
        public string Name { get; set; }
    }
    class Program
    {
        static void Main(string[] args)
        {
            var cars = new List<string>()
            {
                "Car/",
                "Car/BMW/",
                "Car/Great Wall/",
                "Car/Great Wall/Another/",
                "Car/Great Wall/Another/test - file.bak",
                "Car/Great Wall/Another/second - file.bak",
                "Car/Great Wall/Car/",
                "Car/Great Wall/local - copy.bak",
                "Car/Great Wall/local - copy(2).bak",
                "Car/Mercedes/process - file.bak",
                "Car/Mercedes/process - file(2).bak",
                "Car/test123 - file.bak"
            };

            var folders = GetFoldersFormStrings(cars);
            ShowFolders(folders);
        }

        static List<Folder> GetFoldersFormStrings(List<string> strings)
        {
            var folders = new List<Folder>();
            strings.Sort(StringComparer.InvariantCultureIgnoreCase);
            var folderByPath = new Dictionary<string, Folder>();
            foreach (var str in strings)
            {
                if (str.EndsWith("/")) // we have a folder
                {
                    EnsureFolder(folders, folderByPath, str);
                }
                else // we have a file
                {
                    var lastSlashPosition = str.LastIndexOf("/");
                    var parentFolderPath = str.Substring(0, lastSlashPosition + 1);
                    var parentFolder = EnsureFolder(folders, folderByPath, parentFolderPath);
                    var fileName = str.Substring(lastSlashPosition + 1);
                    var file = new File
                    {
                        Name = fileName
                    };
                    parentFolder.Files.Add(file);
                }
            }
            return folders;
        }

        private static Folder EnsureFolder(List<Folder> rootFolders, Dictionary<string, Folder> folderByPath, string folderPath)
        {
            if (!folderByPath.TryGetValue(folderPath, out var folder))
            {
                var folderPathWithoutEndSlash = folderPath.TrimEnd('/');
                var lastSlashPosition = folderPathWithoutEndSlash.LastIndexOf("/");
                List<Folder> folders;
                string folderName;
                if (lastSlashPosition < 0) // it's a first level folder
                {
                    folderName = folderPathWithoutEndSlash;
                    folders = rootFolders;
                }
                else
                {
                    var parentFolderPath = folderPath.Substring(0, lastSlashPosition + 1);
                    folders = folderByPath[parentFolderPath].Folders;
                    folderName = folderPathWithoutEndSlash.Substring(lastSlashPosition + 1);
                }
                folder = new Folder
                {
                    Name = folderName
                };
                folders.Add(folder);
                folderByPath.Add(folderPath, folder);
            }
            return folder;
        }

        private static void ShowFolders(List<Folder> folders)
        {
            foreach (var folder in folders)
            {
                ShowFolder(folder, 0);
            }
        }

        private static void ShowFolder(Folder folder, int indentation)
        {
            string folderIndentation = new string(' ', indentation);
            string fileIndentation = folderIndentation + "  ";
            Console.WriteLine($"{folderIndentation}-{folder.Name}");
            foreach (var file in folder.Files)
            {
                Console.WriteLine($"{fileIndentation}-{file.Name}");
            }
            foreach (var subfolder in folder.Folders)
            {
                ShowFolder(subfolder, indentation + 2);
            }
        }
    }
}

我正在对字符串进行排序,以防止尝试在父文件夹之前创建子文件夹,并防止在创建包含文件夹之前添加文件.

I'm sorting the strings to prevent trying to create a subfolder before the parent folder, and to prevent to add a file before the containing folder is created.

对于每个字符串,如果它以斜杠结尾,则创建一个文件夹,否则我创建文件.我按路径维护一个文件夹字典,以便在需要时获取父文件夹,因此我可以将文件夹或文件添加到包含文件夹中.

for each string, if it ends with slash then a create a folder, else I create the file. I maintain a dictionary of folders by path to get the parent folder when needed, so I can add a folder or a file to the containing folder.

为了显示文件夹结构,我使用了一种递归算法,当您深入到树中时,它会增加缩进.

To show the folder structure I use a recursive algorithm that increments the indentation as you go deep into the tree.

剩下的只是字符串操作.

The rest is just string manipulation.

这是程序的输出:

-Car
  -test123 - file.bak
  -BMW
  -Great Wall
    -local - copy(2).bak
    -local - copy.bak
    -Another
      -second - file.bak
      -test - file.bak
    -Car
  -Mercedes
    -process - file(2).bak
    -process - file.bak

这篇关于使用 c# 从字符串路径构建文件夹/文件树的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆