String List of filepaths to structured object

72 views Asked by At

I'm currently creating an MVC page that will scan a folder and its children for all pdf files and display them. Allowing the user to click on a link and open the document.

I have the following list of paths in List format.

Docs\\Work\\Test\\TestFile0.pdf
Docs\\Work\\Test\\TEstFile1.pdf
Docs\\Work\\Job\\JobFile0.pdf
Docs\\Work\\Job\\JobFile1.pdf
Docs\\School\\English\\Eng0.pdf
Docs\\School\\English\\Eng1.pdf
Docs\\School\\German\\Ger0.pdf
Docs\\School\\German\\Ger0.pdf
Docs\\Games\\Game0.pdf
Docs\\Games\\Game1.pdf
Docs\\Games\\Game2.pdf

I want to create a tree structure out of these that I can send to my View. Here is my model currently

public class FolderModel
{
    public string Name { get; set; }
    public List<FolderModel> ChildFolders { get; set; }
    public List<FileModel> ChildFiles { get; set; }

    public FolderModel()
    {
        ChildFolders = new List<FolderModel>();
        ChildFiles = new List<FileModel>();
    }
}

public class FileModel
{
    public string Name { get; set; }
    public string Path { get; set; }
}

I've tried a number of different ways of doing this but I cannot seem to get it working properly. My current approach is to take each string, split it into a list of strings and use recursion to create folders and their children.

private FolderModel Create(List<string> path, FolderModel model, string origPath)
{
    if (!path.Any())
    {
        return model;
    }
    var firstItem = path.First();
    if (firstItem.Contains("."))
    {
        //its a file
        var file = new FileModel()
        {
            Name = firstItem,
            Path = origPath
        };
        model.ChildFiles.Add(file);
        path.RemoveAt(0);
        model = Create(path, model, origPath);
        return model;
    }
    else
    {
        //its a folder
        var folder = new FolderModel()
        {
            Name = firstItem
        };

        if (!model.ChildFolders.Contains(folder))
        {
            model.ChildFolders.Add(folder);
        }
        path.RemoveAt(0);
        model = Create(path, folder, origPath);
        return model;
    }
}

However I cannot seem to get it working properly and have tried a lot of different methods of doing it. Can anyone lend a hand or point me to something that will help me out.

0

There are 0 answers