Search code examples
c#file-iouwpricheditbox

Acces Denied when I use Open File Picker for open text file for RichEditBox UWP C#


I want to open a text file with Open File Picker and show in a RichEditBox, but when I select the file and push Ok, Visual Studio show "Access Denied", I want to know how to solve this please, there is my code:

var picker = new FileOpenPicker();
        picker.ViewMode = PickerViewMode.Thumbnail;
        picker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;
        picker.FileTypeFilter.Add("*");
        picker.FileTypeFilter.Add(".txt");
        picker.FileTypeFilter.Add(".text");
        picker.FileTypeFilter.Add(".bat");
        picker.FileTypeFilter.Add(".js");
        picker.FileTypeFilter.Add(".vbs");

        StorageFile file = await picker.PickSingleFileAsync();
        if (file != null)
        {
            StorageFolder storageFolder = ApplicationData.Current.LocalFolder;
            StorageFile filepath = await StorageFile.GetFileFromPathAsync(file.Path);
            string text = await FileIO.ReadTextAsync(filepath);
            RichEditBox1.Document.SetText(Windows.UI.Text.TextSetOptions.None, text);

        }

Solution

  • You don't need to call StorageFile.GetFileFromPathAsync(file.Path) since you already have this StorageFile in the file variable returned from PickSingleFileAsync:

        StorageFile file = await picker.PickSingleFileAsync();
        if (file != null)
        {
            string text = await FileIO.ReadTextAsync(file);
            RichEditBox1.Document.SetText(Windows.UI.Text.TextSetOptions.None, text);
        }
    

    The unnecessary GetFileFromPathAsync probably throws an AccessDenied error since the FileOpenPicker provides access only through the returned StorageFile and doesn't give direct access to the file through its path. This behavior is version dependent and new versions of Windows 10 will allow more direct access through file system API (see the Build 2017 talk UWP Apps file access improvements