'C# UWP UnauthorizedAccessException - Access to path is denied

I'm trying to write a list to a txt file via the following code with my UWP app:

string filePath = @"C:\receipt.txt"; File.WriteAllLines(filePath, output);

but I get the following error: System.UnauthorizedAccessException: 'Access to the path 'C:\receipt.txt' is denied.'

I've run VS as admin and added an app manifest and adjusted but still no luck.

Any help would be greatly appreciated.

Edit: I added the broadFileSystemAccess to the program and allowed it permissions through windows settings but still get the same error. Also I changed it to @"C:\Receipts\receipt.txt"; but still no luck. Works fine with framework console app but I think that's because UWP doesn't have same access (at least from what I read online)



Solution 1:[1]

While not the best solution, fix for me was:

Change method to async:

Replace filepath string with

var file = await StorageFile.GetFileFromPathAsync("C:\\Receipts\\receipt.txt");

Replace WriteAllLines() with

await Windows.Storage.FileIO.WriteLinesAsync(file, output);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Jeremy Caney