get all files and directories in C# and set all files and directories in JS
C#
GetFilesAndDirectories(@”C:”, true);
private List<object> GetFilesAndDirectories(string path, bool isRoot = false) {
List<object> fileList = new List<object>();
Dictionary<string, object> fileItem = new Dictionary<string, object>();
if (isRoot) {
fileItem = new Dictionary<string, object>();
fileItem[“type”] = “dir”;
fileItem[“value”] = path.Substring(path.LastIndexOf(Path.DirectorySeparatorChar) + 1);
fileItem[“path”] = path;
fileItem[“fileList”] = GetFilesAndDirectories(path);
fileList.Add(fileItem);
} else {
foreach (string dir in Directory.GetDirectories(path)) {
fileItem = new Dictionary<string, object>();
fileItem[“type”] = “dir”;
fileItem[“value”] = dir.Substring(dir.LastIndexOf(Path.DirectorySeparatorChar) + 1);
fileItem[“path”] = dir;
fileItem[“fileList”] = GetFilesAndDirectories(dir);
fileList.Add(fileItem);
}
foreach (string file in Directory.GetFiles(path)) {
fileItem = new Dictionary<string, object>();
fileItem[“type”] = “file”;
fileItem[“value”] = Path.GetFileName(file);
fileItem[“path”] = file;
fileItem[“exe”] = Path.GetExtension(file);
fileList.Add(fileItem);
}
}
return fileList;
}
JS
getFileInfo (c#returnedFileList, true);
var getFileInfo = function (fileList, isRoot) {
var rtnHtml = “”;
if ($.isArray(fileList)) {
rtnHtml += isRoot || false ? ‘<ul>’ : ‘<ul style=”display:none;”>’;
for (var i = 0, iLen = fileList.length; i < iLen; i++) {
var fileItem = fileList[i];
if (fileItem[“type”] === “dir”) {
rtnHtml += ‘<li><div class=”directory”>’ + fileItem[“value”] + ‘</div>’;
if (fileItem[“fileList”].length !== 0) {
rtnHtml += getFileInfo(fileItem[“fileList”]);
}
} else if (fileItem[“type”] === “file”) {
rtnHtml += ‘<li><div class=”file”>’ + fileItem[“value”] + ‘</div></li>’;
}
}
rtnHtml += ‘</ul>’;
}
return rtnHtml;
};