Reputation: 17
I'm creating a UWP app, and i'm trying to read an image from a file to a Byte[]. I don't know why but i'm always getting the exception from whatever file path... I tried running that same method File.ReadAllBytes from a different project and it didn't throw the exception. Is it a problem of permissions in my project?
Foto = File.ReadAllBytes(@"C:\users\migue\Desktop\aladin.jpg");
<Package
...
xmlns:rescap="http://schemas.microsoft.com/appx/manifest/foundation/windows10/restrictedcapabilities"
IgnorableNamespaces="uap mp uap5 rescap">
...
<Capabilities>
<rescap:Capability Name="broadFileSystemAccess" />
</Capabilities>
I tried using this example code in my appmanifest, but it doesn't work. The code is in microsoft docs page.
Upvotes: 0
Views: 591
Reputation: 7727
Rather than accessing files directly by path, it is recommended to use FileOpenPicker
to open the file in UWP.
You can use this code:
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("File extension is incorrect");
}
var file = await picker.PickSingleFileAsync();
if (file != null)
return file;
else
return null;
}
Usage
var file = await OpenLocalFile(".jpg");
var bytes = (await FileIO.ReadBufferAsync(file)).ToArray();
Best regards.
Upvotes: 1