Reputation: 119
I used JSON.Net to retrieve directory and file structure recursively. Referred this link( Is there a way to directly get a directory structure and parse it to Json in C#?). The result retreived as shown
RootDir
{
"directory":
{
"dirA": {
"file" : [ "file0.txt", "file1.jpg" ]
},
"emptyDir": {
}
},
"file": [ "file2.png" ]
}
But I would like to exclude the "directory" and "file" keywords from the structure. My structure should look like this
RootDir
{
"dirA": {
" "file0.txt", "file1.jpg"
},
"dirB": {
}
},
"file2.png"
I wanted only the directory names and file names rather than getting the directory names under a keyword and filenames under another keyword. Please help.
Thanks
Upvotes: 3
Views: 1846
Reputation: 129687
You can't get exactly the result you showed, because it would be invalid JSON. However, you can come pretty close. Try something like this:
public static string GetDirectoryAsJson(string path)
{
return GetDirectoryAsJObject(new DirectoryInfo(path)).ToString();
}
public static JObject GetDirectoryAsJObject(DirectoryInfo directory)
{
JObject obj = new JObject();
foreach (DirectoryInfo d in directory.EnumerateDirectories())
{
obj.Add(d.Name, GetDirectoryAsJObject(d));
}
foreach (FileInfo f in directory.GetFiles())
{
obj.Add(f.Name, JValue.CreateNull());
}
return obj;
}
Then use it like this (for example):
string json = GetDirectoryAsJson(@"C:\Users\JohnDoe\Documents");
If the folder structure inside C:\Users\JohnDoe\Documents
looked like this:
dirA
dirA1
foo.txt
file0.txt
file1.jpg
dirB
file2.png
Then the resulting JSON would look like this:
{
"dirA": {
"dirA1": {
"foo.txt": null
},
"file0.txt": null,
"file1.jpg": null
},
"dirB": {},
"file2.png": null
}
Upvotes: 1