Ralph Marvin
Ralph Marvin

Reputation: 149

How to access user files?

I am developing a Windows 10 UWP application and anytime I run the below code, I get the following execption:

'UnauthorizedAccessException - Access to path {path name} is denied'.

I have tried the several windows folders (path) :

  1. Pictures,
  2. Videos
  3. Desktop etc.

This is my code:

public async Task GetFiles() // edit added wrapper method for readability
{
    var filePicker = new FileOpenPicker();
    filePicker.FileTypeFilter.Add("*");

    Windows.Storage.StorageFile file = await filePicker.PickSingleFileAsync();

    if (file != null)
    {
        ChosenFiles.ItemsSource = GetFileInfo(file.Path);
    }
}

public List<string> GetFileInfo(string path)
{
    List<string> files = new List<string>();
    string[] allFiles = Directory.GetFiles(path);

    foreach (var file in allFiles)
    {
        FileInfo Info = new FileInfo(file);
        files.Add(Info.Name);
    }

    return files;
}

Upvotes: 1

Views: 107

Answers (1)

Andrei Ashikhmin
Andrei Ashikhmin

Reputation: 2451

System.IO.Directory seems to only have direct access to app package and app local storage folders. That means you should rather use StorageFile and StorageFolder classes to extract information you need. For example:

private async void ButtonBase_OnClick(object sender, RoutedEventArgs args)
{
    var folderPicker = new FolderPicker();

    var folder = await folderPicker.PickSingleFolderAsync();

    if (folder != null)
    {
        ChosenFiles.ItemsSource = await GetFileInfoAsync(folder);
    }
}


public async Task<List<string>> GetFileInfoAsync(StorageFolder folder)
{
    List<string> files = new List<string>();
    var allFiles = await folder.GetFilesAsync();

    foreach (var file in allFiles)
    {
        files.Add(file.Name);
    }

    return files;
}

Note that if you picked a file, you can't enumerate its neighbors because you don't have access to its parent folder. So for your scenario you should use FolderPicker.

Upvotes: 1

Related Questions