使用以下代码:
static void Main(string[] args)
{
JObject fileSystemTree = CreateFileSystemJsonTree("C:/DirectoryTree");
Console.WriteLine(fileSystemTree);
Console.WriteLine("------");
//
// Write it out to a file
//
System.IO.File.WriteAllText(@"C:\jsontree.txt", fileSystemTree.ToString());
Console.ReadLine();
}
static JObject joNew = new JObject();
static JObject CreateFileSystemJsonTree(string source)
{
//
// Build a list of all the IPs
//
//Console.WriteLine(source);
using (var poiDbContext = new poiDbEntities())
{
DirectoryInfo di = new DirectoryInfo(source);
{
joNew = new JObject(
new JProperty(di.Name, new JArray(Directory.GetDirectories(source).Select(d => CreateFileSystemJsonTree(d)))),
new JProperty("files", new JArray(di.GetFiles().Select(fi => new JObject(new JProperty(fi.Name, GetText(fi.Name)))))));
}
Console.WriteLine(joNew);
}
return joNew;
}
public static string GetText(string fiName)
{
using (var poiDbContext = new poiDbEntities())
{
string indexNameBody = fiName.Substring(0, fiName.LastIndexOf('.'));
var indexResult = "test"; // dummied up for use by evaluators
return indexResult.Trim();
}
}
我正在尝试使用递归从系统目录创建文件树。我有这个使用 XML,但更喜欢 JSON 树。问题是出现了 txt 文件,而不是父的 [],它代表最低的文件夹,而是被添加为 JsonProperties,我添加了作为“文件”的文本名称(我不想要)。另外,即使没有文件,例如在空文件夹中,也会生成“文件”。系统生成的片段后面是可能需要的片段。
"Sports": [
{
"NBA": [],
"files": [] // Undesirable--The folder is empty``
},``
两个片段:
{
"Politics": [
{
"PresCandidates": [
{
"Republican": [], // Notice the files are not in array within the [] of the Republican
"files": [
{
"carson_ben_s.txt": "Ben Carson"
},
{
"trump_donald_j.txt": "Donald Trump"
},
{
"walker_scott_k.txt": "Scott Walker"
}
]
}
]
}
],
"Politics": [ // The desired format
{
"PresCandidates": [
{
"Republican": [
{
"carson_ben_s.txt": "Ben Carson"
},
{
"trump_donald_j.txt": "Donald Trump"
},
{
"walker_scott_k.txt": "Scott Walker"
}
],
{