C#使用递归动态映射文件系统
我正在尝试使用C#将文件夹结构动态映射为JSON格式 以下是我的方法:C#使用递归动态映射文件系统,c#,json,recursion,C#,Json,Recursion,我正在尝试使用C#将文件夹结构动态映射为JSON格式 以下是我的方法: public static string StartJson(string Dir) { try { StringBuilder Json = new StringBuilder(); Json.Append("{\"FileSystem\" : ["); if (Directory.GetDirectories(Dir).ToList().Count >
public static string StartJson(string Dir)
{
try
{
StringBuilder Json = new StringBuilder();
Json.Append("{\"FileSystem\" : [");
if (Directory.GetDirectories(Dir).ToList().Count > 0)
{
Json.Append(GetDirectoryJson(Dir, 0));
}
if(Directory.GetFiles(Dir).ToList().Count > 0 && Directory.GetDirectories(Dir).ToList().Count == 0)
{
Json.Append(GetFileJSON(Dir));
}
else if(Directory.GetFiles(Dir).ToList().Count > 0 && Directory.GetDirectories(Dir).ToList().Count > 0)
{
Json.Append(",");
Json.Append("{");
Json.Append(GetFileJSON(Dir));
Json.Append("}");
}
Json.Append("]}");//Close FileSystem
return Json.ToString();
}
catch(Exception e) { return ""; }
}
public static int count = 0;
public static string GetDirectoryJson(string Dir, int Iteration)
{
try
{
string path1 = Directory.GetParent(Dir).FullName;
bool p = path.Equals(Directory.GetParent(Dir).FullName);
StringBuilder Json = new StringBuilder();
int folders = Directory.GetDirectories(path).ToList().Count;
foreach (string DirectoryPath in Directory.GetDirectories(Dir))
{
Json.Append("{");
Json.Append("\"Folder\": [{");
Json.Append("\"FolderPath\": " + "\"" + DirectoryPath.Replace('\\', '/') + "\"");
if(Directory.GetDirectories(DirectoryPath).ToList().Count > 0)
{
Json.Append(",");
Json.Append("\"Sub\": [");
count++;
Json.Append(GetDirectoryJson(DirectoryPath, Iteration++));
Json.Append("]");
}
if (Directory.GetFiles(DirectoryPath).ToList().Count > 0)
{
Json.Append(",");
Json.Append(GetFileJSON(Dir));
}
Json.Append("}");
Json.Append("]");
Json.Append("}");
}
return Json.ToString();
}
catch (Exception e) { return "Fail"; }
}
public static string GetFileJSON(string Dir)
{
try
{
StringBuilder Json = new StringBuilder();
Json.Append("\"Files\": [");
int FileCount = 0;
foreach (string FilePath in Directory.GetFiles(Dir))
{
Json.Append("{\"FilePath\": " + "\"" + FilePath.Replace('\\', '/') + "\"");
FileCount++;
if (Directory.GetFiles(Dir).ToList().Count == FileCount)
Json.Append("}");
else
Json.Append("},");
}
Json.Append("]");
return Json.ToString();
}
catch(Exception e) { return ""; }
}
我真的很接近了,因为当我使用我的测试文件夹时,这输出了大部分正确的JSON:“C:\Users\sredmond.QPS\u DOMAIN\Documents\test”
我得到了以下JSON:
{
"FileSystem":[
{
"Folder":[
{
"FolderPath":"C:/Users/sredmond.QPS_DOMAIN/Documents/Test/Sub1",
"Sub":[
{
"Folder":[
{
"FolderPath":"C:/Users/sredmond.QPS_DOMAIN/Documents/Test/Sub1/CantLogin_files",
"Sub":[
{
"Folder":[
{
"FolderPath":"C:/Users/sredmond.QPS_DOMAIN/Documents/Test/Sub1/CantLogin_files/images",
"Files":[
{
"FilePath":"C:/Users/sredmond.QPS_DOMAIN/Documents/Test/Sub1/CantLogin_files/CheckBrowser.js.download"
},
{
"FilePath":"C:/Users/sredmond.QPS_DOMAIN/Documents/Test/Sub1/CantLogin_files/footer_right.jpg"
},
{
"FilePath":"C:/Users/sredmond.QPS_DOMAIN/Documents/Test/Sub1/CantLogin_files/ga.js.download"
},
{
"FilePath":"C:/Users/sredmond.QPS_DOMAIN/Documents/Test/Sub1/CantLogin_files/igpnl_up.gif"
},
{
"FilePath":"C:/Users/sredmond.QPS_DOMAIN/Documents/Test/Sub1/CantLogin_files/ig_panel.css"
},
{
"FilePath":"C:/Users/sredmond.QPS_DOMAIN/Documents/Test/Sub1/CantLogin_files/ig_shared.css"
},
{
"FilePath":"C:/Users/sredmond.QPS_DOMAIN/Documents/Test/Sub1/CantLogin_files/jquery-1.9.0.min.js.download"
},
{
"FilePath":"C:/Users/sredmond.QPS_DOMAIN/Documents/Test/Sub1/CantLogin_files/jquery.browser.js.download"
},
{
"FilePath":"C:/Users/sredmond.QPS_DOMAIN/Documents/Test/Sub1/CantLogin_files/jquery.cookie.js.download"
},
{
"FilePath":"C:/Users/sredmond.QPS_DOMAIN/Documents/Test/Sub1/CantLogin_files/qps_logo.png"
},
{
"FilePath":"C:/Users/sredmond.QPS_DOMAIN/Documents/Test/Sub1/CantLogin_files/QPS_New.css"
},
{
"FilePath":"C:/Users/sredmond.QPS_DOMAIN/Documents/Test/Sub1/CantLogin_files/ScriptResource(1).axd"
},
{
"FilePath":"C:/Users/sredmond.QPS_DOMAIN/Documents/Test/Sub1/CantLogin_files/ScriptResource(2).axd"
},
{
"FilePath":"C:/Users/sredmond.QPS_DOMAIN/Documents/Test/Sub1/CantLogin_files/ScriptResource(3).axd"
},
{
"FilePath":"C:/Users/sredmond.QPS_DOMAIN/Documents/Test/Sub1/CantLogin_files/ScriptResource(4).axd"
},
{
"FilePath":"C:/Users/sredmond.QPS_DOMAIN/Documents/Test/Sub1/CantLogin_files/ScriptResource.axd"
},
{
"FilePath":"C:/Users/sredmond.QPS_DOMAIN/Documents/Test/Sub1/CantLogin_files/secondaryNavBG_right.jpg"
},
{
"FilePath":"C:/Users/sredmond.QPS_DOMAIN/Documents/Test/Sub1/CantLogin_files/WebResource.axd"
}
]
}
]
}
],
"Files":[
{
"FilePath":"C:/Users/sredmond.QPS_DOMAIN/Documents/Test/Sub1/CantLogin.html"
},
{
"FilePath":"C:/Users/sredmond.QPS_DOMAIN/Documents/Test/Sub1/UsersAndPass.csv"
}
]
}
]
}
],
"Files":[
{
"FilePath":"C:/Users/sredmond.QPS_DOMAIN/Documents/Test/New Hire Reporting Form - Copy.pdf"
},
{
"FilePath":"C:/Users/sredmond.QPS_DOMAIN/Documents/Test/New Hire Reporting Form.pdf"
}
]
}
]
} {
"Folder":[
{
"FolderPath":"C:/Users/sredmond.QPS_DOMAIN/Documents/Test/Sub2",
"Sub":[
{
"Folder":[
{
"FolderPath":"C:/Users/sredmond.QPS_DOMAIN/Documents/Test/Sub2/Test",
"Files":[
{
"FilePath":"C:/Users/sredmond.QPS_DOMAIN/Documents/Test/Sub2/UsersAndPass - Big (737).csv"
}
]
}
]
}
],
"Files":[
{
"FilePath":"C:/Users/sredmond.QPS_DOMAIN/Documents/Test/New Hire Reporting Form - Copy.pdf"
},
{
"FilePath":"C:/Users/sredmond.QPS_DOMAIN/Documents/Test/New Hire Reporting Form.pdf"
}
]
}
]
} {
"Folder":[
{
"FolderPath":"C:/Users/sredmond.QPS_DOMAIN/Documents/Test/Sub3"
}
]
},
{
"Files":[
{
"FilePath":"C:/Users/sredmond.QPS_DOMAIN/Documents/Test/New Hire Reporting Form - Copy.pdf"
},
{
"FilePath":"C:/Users/sredmond.QPS_DOMAIN/Documents/Test/New Hire Reporting Form.pdf"
}
]
}
]
}
正如您所看到的,JSON几乎是正确的,但是在根目录中没有分隔文件夹的逗号。您可以将JSON放在这里:并亲自查看错误发生的位置
不管怎么说,我的问题是如何使这些逗号放在正确的位置。每次我尝试添加逗号或在其中添加条件时,都会将逗号放在JSON中的随机点中。问题隐藏在最后一个
JSON.Append(“}”)
您需要在同一级别的目录之间添加逗号。如果有一个更宽的目录树,您将看到更多的逗号问题
话虽如此,正如建议的那样,您最好使用一个完善的库,该库已经过测试并被许多人使用过,如谢谢大家的回答。在深入研究JSON.NET之后,我在这里找到了一个很好的答案:不要通过字符串操作创建JSON 我将创建一个自定义类文件夹并使用递归方法
public class Folder
{
public string Path { set; get; }
public List<string> Files { set; get; }
public List<Folder> SubFolders { set; get; }
}
Folder GetFolderHierarchy(string root)
{
var folder = new Folder();
var dir = new DirectoryInfo(root);
folder.Path = root;
folder.Files = dir.GetFiles().Select(x => x.FullName).ToList();
folder.SubFolders = dir.GetDirectories().Select(x => GetFolderHierarchy(x.FullName))
.ToList();
return folder;
}
添加
如果要存储相对路径而不是完整路径,可以将该方法更改为:
Folder GetFolderHierarchy(string root)
{
var folder = new Folder();
var dir = new DirectoryInfo(root);
folder.Files = dir.GetFiles().Select(x => x.Name).ToList();
folder.Path = dir.Name;
folder.SubFolders = dir.GetDirectories().Select(x => GetFolderHierarchy(x.FullName))
.ToList();
return folder;
}
与其从头开始编写json,为什么不创建一个树状视图,然后使用json.net进行解析^I如何获得树状视图?我将展示,仅两分钟,我应该提到这是一个Web服务,它应该返回一个json对象,以便JavaScript进行解析,并创建一个文件夹视图,无论其目的是什么,您通常不应该自己操作或构建JSON文本。相反,构建一个表示数据的类结构,填写数据结构的实例,然后使用类似JSON.Net的库从数据构建JSON。
Folder GetFolderHierarchy(string root)
{
var folder = new Folder();
var dir = new DirectoryInfo(root);
folder.Files = dir.GetFiles().Select(x => x.Name).ToList();
folder.Path = dir.Name;
folder.SubFolders = dir.GetDirectories().Select(x => GetFolderHierarchy(x.FullName))
.ToList();
return folder;
}