且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何解决 UWP 应用程序读取文件时权限被拒绝的问题?

更新时间:2023-11-20 21:08:10

正如 Adam McMahon 所说,UWP 应用是沙盒应用,不直接访问外部环境中的文件.对于文件权限,您可以查看此文档.

As Adam McMahon said, UWP apps are sandboxed apps and don't directly access files in the external environment. For file permissions, you can view this document.

针对您提供的示例,您可以使用 FileOpenPicker 选择一个文本文件并从获取的 StorageFile 中读取内容.

Specific to the example you provided, you can use FileOpenPicker to select a text file and read the contents from the obtained StorageFile.

此示例仅供参考:

public async static Task<StorageFile> OpenLocalFile(params string[] types)
{
    var picker = new FileOpenPicker();
    picker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;
    Regex typeReg = new Regex(@"^\.[a-zA-Z0-9]+$");
    foreach (var type in types)
    {
        if (type == "*" || typeReg.IsMatch(type))
            picker.FileTypeFilter.Add(type);
        else
            throw new InvalidCastException("Invalid extension");
    }
    var file = await picker.PickSingleFileAsync();
    if (file != null)
        return file;
    else
        return null;
}

使用

var txtFile=await OpenLocalFile(".txt");
if(txtFile!=null)
{
    var lines = FileIO.ReadLinesAsync(txtFile);
    // ... Other code
}

***的问候.