我有一个字符串数组,存储了一些文件路径:
path/to/folder/file.xxx
path/to/other/
path/to/file/file.xx
path/file.x
path/
我该如何将这个列表转换为树形结构?到目前为止,我有以下内容:
/// <summary>
/// Enumerates types of filesystem nodes.
/// </summary>
public enum FilesystemNodeType
{
/// <summary>
/// Indicates that the node is a file.
/// </summary>
File,
/// <summary>
/// Indicates that the node is a folder.
/// </summary>
Folder
}
/// <summary>
/// Represents a file or folder node.
/// </summary>
public class FilesystemNode
{
private readonly ICollection<FilesystemNode> _children;
/// <summary>
/// Initializes a new instance of the <see cref="FilesystemNode"/> class.
/// </summary>
public FilesystemNode()
{
_children = new LinkedList<FilesystemNode>();
}
/// <summary>
/// Gets or sets the name of the file or folder.
/// </summary>
public string Name { get; set; }
/// <summary>
/// Gets or sets the full path to the file or folder from the root.
/// </summary>
public string Path { get; set; }
/// <summary>
/// Gets or sets a value indicating whether the node is a file or folder.
/// </summary>
public FilesystemNodeType Type { get; set; }
/// <summary>
/// Gets a list of child nodes of this node. The node type must be a folder to have children.
/// </summary>
public ICollection<FilesystemNode> Children
{
get
{
if (Type == FilesystemNodeType.Folder)
return _children;
throw new InvalidOperationException("File nodes cannot have children");
}
}
}
我有点不知道如何划分路径。任何以 / 结尾的路径都是目录,任何不以 / 结尾的路径都不是。
另外,如果我的输入没有包含文件夹的路径,我该怎么办呢?
例如,如果我的输入是:
path/to/file.c
path/file.c
path/
如何解释输入中不包含path/to/
这一事实?
directory1/subdirectory/files
中获取subdirectory
的子项? - m.qayyum