Created
November 2, 2018 17:58
-
-
Save DevEarley/72e8d313747e798f793ec441ca35dc76 to your computer and use it in GitHub Desktop.
Read folders recursively in .Net Core
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
namespace App | |
{ | |
public class FileReader | |
{ | |
private List<FolderModel> GetFoldersForDocs() | |
{ | |
DirectoryInfo di = new DirectoryInfo(documentationPath); | |
FileInfo[] files = RecursiveFetch(4, di.FullName); | |
var trimLength = di.FullName.Count(); | |
var folders = files.Select(x => BuildFileModel(x, trimLength)) | |
.Distinct() | |
.GroupBy(file => file.pathParts[0], | |
file => file, | |
(key, fileGroup) => BuildFolder(key, fileGroup)) | |
.ToList(); | |
return folders; | |
} | |
private DocModel GetFile(string filename) | |
{ | |
filename = filename.Replace("|", "\\"); | |
DirectoryInfo di = new DirectoryInfo(documentationPath); | |
FileInfo[] files = RecursiveFetch(4, di.FullName); | |
var result = files.FirstOrDefault(x => x.FullName == filename); | |
if (result == null) return new DocModel { content = filename }; | |
using (StreamReader streamReader = result.OpenText()) | |
{ | |
string s = ""; | |
s = streamReader.ReadToEnd(); | |
return new DocModel { content = s }; | |
} | |
} | |
private FolderModel BuildFolder(string key, IEnumerable<FileModel> fileGroup) | |
{ | |
return new FolderModel { name = key, files = fileGroup.ToArray() }; | |
} | |
private static FileModel BuildFileModel(FileInfo x, int trimLength) | |
{ | |
var length = x.FullName.Count() - trimLength; | |
var trimmedPath = x.FullName.Substring(trimLength, length).ToString(); | |
var splitPath = trimmedPath.Split('\\'); | |
return new FileModel | |
{ | |
name = x.Name, | |
path = x.FullName, | |
trimmedPath = trimmedPath, | |
createdDate = x.CreationTime, | |
modifiedDate = x.LastWriteTime, | |
pathParts = | |
splitPath.TakeLast(4).ToArray(), | |
pathPartsIsPartial = | |
(splitPath.Count() > pathPartsMaxCount), | |
pathPartCount = splitPath.Count() | |
}; | |
} | |
private FileInfo[] RecursiveFetch(int? depth, string path) | |
{ | |
var currentDirectory = new DirectoryInfo(path); | |
var currentFiles = currentDirectory.GetFiles("*.md"); | |
depth--; | |
if (depth <= 0 && depth != null) return currentFiles; | |
var children = Directory.GetDirectories(path).Where(x => x.Contains("node_modules") == false); | |
foreach (var di in children) | |
{ | |
FileInfo[] noFiles = { }; | |
var morefiles = RecursiveFetch(depth, di); | |
currentFiles = currentFiles.Concat(morefiles).ToArray(); | |
} | |
return currentFiles; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment