Reputation: 2280
We need to store an image file as a string in a UWP app. This was the plan:
FileOpenPicker picker = new FileOpenPicker();
picker.FileTypeFilter.Add(".png");
StorageFile file = await picker.PickSingleFileAsync();
byte[] fileBytes = File.ReadAllBytes(file.Path);
string fileString = Convert.ToBase64String(fileBytes);
but the line
byte[] fileBytes = File.ReadAllBytes(file.Path);
throws
System.UnauthorizedAccessException Access to the path 'C:\MyFolder\ImageFile.png' is denied.
For this exercise Everyone has Full Control permission on the file. I've also moved the file to various locations including a USB stick but always get the same exception. I assume this is a UWP thing rather than a permissions thing?
How do we save an image file as a string in a UWP app?
Upvotes: 1
Views: 1351
Reputation: 1638
You get the exception, because in UWP you only can access to files over the path, is in the App-Package area.
To solve your problem you can use the IBuffer
extension ToArray
:
IBuffer buffer = await FileIO.ReadBufferAsync(file);
string fileString = Convert.ToBase64String(buffer.ToArray());
Upvotes: 2
Reputation: 600
you can't directly access to a file with string path. In UWP, you should always access file with Storage(File, Folder)check this
to get Bytes, you can use FileIO class or Open Stream with StorageFile.
Upvotes: 0