I'm trying to use the following code to save the contents of myCanvas as an image file in the gallery (for Windows Phone 8.1, not Silverlight). When I run the app and call SaveFileToPhone(), it throws System.UnauthorizedAccessException.
I have already checked the Capabilities in the Manifest file and they seem to be fine. What am I doing wrong. I've read through a lot of resources but couldn't find a solution, Please Help!
I'm still a noob and I tried using the code I found online.
public async void SaveFileToPhone()
{
var file = await KnownFolders.PicturesLibrary.CreateFileAsync("bug.jpeg", CreationCollisionOption.GenerateUniqueName);
var outStream = await file.OpenAsync(FileAccessMode.ReadWrite);
await SaveVisualElementToFile(myCanvas, file);
outStream.Dispose();
}
async Task SaveVisualElementToFile(FrameworkElement element, StorageFile file)
{
string fileName = "customphoto.jpg";
var renderTargetBitmap = new RenderTargetBitmap();
await renderTargetBitmap.RenderAsync(element, (int)element.Width, (int)element.Height);
var pixels = await renderTargetBitmap.GetPixelsAsync();
using (IRandomAccessStream stream = await file.OpenAsync(FileAccessMode.ReadWrite))
{
var encoder = await
BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, stream);
byte[] bytes = pixels.ToArray();
encoder.SetPixelData(BitmapPixelFormat.Bgra8,
BitmapAlphaMode.Ignore,
(uint)element.Width, (uint)element.Height,
96, 96, bytes);
await encoder.FlushAsync();
}
}
- $exception {System.UnauthorizedAccessException: Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED)) at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult() at ChoosersLaunchers8._1.PhotoChooser.d__1e.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Runtime.CompilerServices.TaskAwaiter.GetResult()
at ChoosersLaunchers8._1.PhotoChooser.d__17.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.AsyncMethodBuilderCore.b__3(Object state) at System.Threading.WinRTSynchronizationContext.Invoker.InvokeCore()} System.Exception {System.UnauthorizedAccessException}