Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get files & folders recursively in Windows Store Applications

Previously in Windows Forms applications, this was how I searched a folder recursively for all files. I know that Windows Store applications are pretty much sandboxed however there must be a way to get all the files in a KnownFolder directory. I've been trying to do this with the music directory. However, it is not working for me. I've done my Googling and I can't find any thread that states how to achieve this. I have tried the following code:

private async void dirScan(string dir)
    {
        var folDir = await StorageFolder.GetFolderFromPathAsync(dir);
        foreach (var d in await folDir.GetFoldersAsync())
        {
            foreach(var f in await d.GetFilesAsync())
            {
                knownMusicDir.Add(f.Path.ToString());
            }
            dirScan(d.ToString());
        }
    }

I hope someone can take a look at my code and hopefully correct it. Thanks in advance!

like image 223
kiyui Avatar asked Feb 13 '23 14:02

kiyui


2 Answers

You can use this extension method:

public static async Task<IEnumerable<StorageFile>> GetAllFilesAsync(this StorageFolder folder)
{
        IEnumerable<StorageFile> files = await folder.GetFilesAsync();
        IEnumerable<StorageFolder> folders = await folder.GetFoldersAsync();
        foreach (StorageFolder subfolder in folders)
            files = files.Concat(await subfolder.GetAllFilesAsync());
        return files;
}
like image 86
Cem Mutlu Avatar answered Feb 16 '23 02:02

Cem Mutlu


This works for me for KnownFolders:

ObservableCollection<string> files; 

public MainPage()
{
    this.InitializeComponent();
    files = new ObservableCollection<string>();
}

private async void GetFiles(StorageFolder folder)
{
    StorageFolder fold = folder;

    var items = await fold.GetItemsAsync();

    foreach (var item in items)
    {
        if (item.GetType() == typeof(StorageFile))
            files.Add(item.Path.ToString());
        else
            GetFiles(item as StorageFolder);
    }

    listView.ItemsSource = files;      
}
like image 43
w.b Avatar answered Feb 16 '23 02:02

w.b