html目录树路径,转换目录路径JSON目录树表示

我终于开始为你制作样品了。这应该是一个很好的可扩展的递归解决方案。 :)

static void Main(string[] args)

{

Node root = new Node("/");

AddNode("New Text Document.txt", root);

AddNode("New folder/", root);

AddNode("New folder/README.txt", root);

Console.ReadKey();

}

public class Node

{

public Node() { Nodes = new List(); }

public Node(string fileName)

{

Nodes = new List();

Data = fileName;

}

public Node FindNode(string data)

{

if (this.Nodes == null || !this.Nodes.Any()) { return null; }

// check Node list to see if there are any that already exist

return this.Nodes

.FirstOrDefault(n => String.Equals(n.Data, data, StringComparison.CurrentCultureIgnoreCase));

}

public string Data { get; set; }

public List Nodes { get; set; }

}

public static Node AddNode(string filePath, Node rootNode)

{

// convenience method. this creates the queue that we need for recursion from the filepath for you

var tokens = filePath.Split('/').ToList();

// if you split a folder ending with/it leaves an empty string at the end and we want to remove that

if (String.IsNullOrWhiteSpace(tokens.Last())) { tokens.Remove(""); }

return AddNode(new Queue(tokens), rootNode);

}

private static Node AddNode(Queue tokens, Node rootNode)

{

// base case -> node wasnt found and tokens are gone :(

if (tokens == null || !tokens.Any())

{

return null;

}

// get current token, leaving only unsearched ones in the tokens object

string current = tokens.Dequeue();

// create node if not already exists

Node foundNode = rootNode.FindNode(current);

if (foundNode != null)

{

// node exists! recurse

return AddNode(tokens, foundNode);

}

else

{

// node doesnt exist! add it manually and recurse

Node newNode = new Node() { Data = current };

rootNode.Nodes.Add(newNode);

return AddNode(tokens, newNode);

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值