代码之家  ›  专栏  ›  技术社区  ›  Miguel Genaro

当我为RichEditBox UWP C的打开文本文件使用打开文件选择器时,访问被拒绝#

  •  2
  • Miguel Genaro  · 技术社区  · 6 年前

    我想用open file Picker打开一个文本文件并在RichEditBox中显示,但当我选择该文件并按“确定”时,Visual Studio显示“拒绝访问”,我想知道如何解决此问题,请输入我的代码:

    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);
    
            }
    
    1 回复  |  直到 6 年前
        1
  •  3
  •   Rob Caplan - MSFT    6 年前

    你不需要打电话 StorageFile.GetFileFromPathAsync(file.Path) 因为您在 file 从PickSingleFileAsync返回的变量:

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

    不必要的GetFileFromPathAsync可能会引发AccessDenied错误,因为FileOpenPicker仅通过返回的存储文件提供访问,而不通过其路径直接访问文件。此行为取决于版本,新版本的Windows 10将允许通过文件系统API进行更直接的访问(请参阅Build 2017 talk UWP Apps file access improvements