UWP StrorageFileGetFilePathAsync()

Paul Ryan 316 Reputation points
2020-04-29T23:41:57.367+00:00

HI, I am trying to figure out how I run this synch

private async Task ReadPtFileAsync( )
{
string path = @"c:\Users\pryan\OneDrive\MUA_Data\Patients.json";
var file = await StorageFile.GetFileFromPathAsync(path);
json = await FileIO.ReadTextAsync(file);
pts.PtList = JsonConvert.DeserializeObject<List<Patient>>(json);
}

thanks for the help

Universal Windows Platform (UWP)
{count} votes

Accepted answer
  1. Daniele 1,996 Reputation points
    2020-04-30T16:26:49.517+00:00

    Try with

    var file = StorageFile.GetFileFromPathAsync(path).GetAwaiter().GetResult();
    string json = FileIO.ReadTextAsync(file).GetAwaiter().GetResult();
    

1 additional answer

Sort by: Most helpful
  1. Xiaodi Yan 876 Reputation points MVP
    2020-04-30T02:41:12.453+00:00

    The StorageFile API can only reads/writes the files in some specific folders, like LocalState, PictureLibrary, etc. Please see the document here: https://learn.microsoft.com/en-us/windows/uwp/files/file-access-permissions

    If you want to read files out of these folders, you need to declare the broadFileSystemAccess capability in the app manifest or call the file picker.

    Example:

    <Package  
      ...  
      xmlns:rescap="http://schemas.microsoft.com/appx/manifest/foundation/windows10/restrictedcapabilities"  
      IgnorableNamespaces="uap mp rescap">  
    ...  
    <Capabilities>  
        <rescap:Capability Name="broadFileSystemAccess" />  
    </Capabilities>  
    

    From your code, I guess you are trying to read the files in OneDrive so you may need more permissions for this folder.

    You could use a try-catch block to wrapper your code and see if there are any exceptions.