How to solve the problem of Permission denied while reading a file from UWP application?

后端 未结 3 407
梦如初夏
梦如初夏 2021-01-27 11:21

I am trying to reading a .txt file of C or D drive in a UWP application. It is ok, when I declare the local variable for file name in assets. But it\'s filed to read file from o

3条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-27 11:34

    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.

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

    This example is for reference:

    public async static Task 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;
    }
    

    Usage

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

    Best regards.

提交回复
热议问题