Search code examples
c#filerecursionwindows-runtimewindows-store-apps

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!


Solution

  • 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;      
    }