I have a sample output of the file paths, this is just an example the for the question
New Text Document.txt
New folder/
New folder/README.txt
which I would like to convert to the following JSON
{
"Data":"/",
"Nodes":[
{
"Data":"New Folder",
"Nodes":[
{
"Data":"New Text Document.txt"
}
]
},
{
"Data":"New Text Document.txt",
"Nodes":[
""
]
}
]
}
My Node Class is the following
public class Node
{
public Node(string fileName)
{
Nodes = new List<Node>();
Data = fileName;
}
public List<Node> Nodes { get; set; }
public string Data { get; set; }
}
I'm trying to figure out the algorithm, how to represent file paths in the as a Node class which I will serialize later to get the JSON. If there is any other way to represent file paths as Directory Tree structured JSON please suggest
Brad C :
I finally got around to making a sample for you. This should be a nicely scalable recursive solution. :)\n\nstatic void Main(string[] args)\n{\n Node root = new Node(\"/\");\n AddNode(\"New Text Document.txt\", root);\n AddNode(\"New folder/\", root);\n AddNode(\"New folder/README.txt\", root);\n\n Console.ReadKey();\n}\n\npublic class Node\n{\n public Node() { Nodes = new List<Node>(); }\n public Node(string fileName)\n {\n Nodes = new List<Node>();\n Data = fileName;\n }\n\n public Node FindNode(string data)\n {\n if (this.Nodes == null || !this.Nodes.Any()) { return null; }\n\n // check Node list to see if there are any that already exist\n return this.Nodes\n .FirstOrDefault(n => String.Equals(n.Data, data, StringComparison.CurrentCultureIgnoreCase));\n }\n\n public string Data { get; set; }\n public List<Node> Nodes { get; set; }\n}\n\npublic static Node AddNode(string filePath, Node rootNode)\n{\n // convenience method. this creates the queue that we need for recursion from the filepath for you\n var tokens = filePath.Split('/').ToList();\n\n // if you split a folder ending with / it leaves an empty string at the end and we want to remove that\n if (String.IsNullOrWhiteSpace(tokens.Last())) { tokens.Remove(\"\"); }\n\n return AddNode(new Queue<string>(tokens), rootNode);\n}\n\nprivate static Node AddNode(Queue<string> tokens, Node rootNode)\n{\n // base case -> node wasnt found and tokens are gone :(\n if (tokens == null || !tokens.Any())\n {\n return null;\n }\n\n // get current token, leaving only unsearched ones in the tokens object\n string current = tokens.Dequeue();\n\n // create node if not already exists\n Node foundNode = rootNode.FindNode(current);\n if (foundNode != null)\n {\n // node exists! recurse\n return AddNode(tokens, foundNode);\n }\n else\n {\n // node doesnt exist! add it manually and recurse\n Node newNode = new Node() { Data = current };\n rootNode.Nodes.Add(newNode);\n return AddNode(tokens, newNode);\n }\n}\n",
2015-05-20T04:01:02