在 Windows Phone 8.1 中保存图像文件时发生 UnauthorizedAccessException

UnauthorizedAccessException while saving an image file in Windows Phone 8.1

我正在尝试使用以下代码将 myCanvas 的内容保存为图库中的图像文件(适用于 Windows Phone 8.1,不适用于 Silverlight)。当我 运行 应用程序并调用 SaveFileToPhone() 时,它抛出 System.UnauthorizedAccessException。
我已经检查了Manifest文件中的Capabilities,它们似乎没问题。我究竟做错了什么。我已经阅读了很多资源,但找不到解决方案,请帮助!

我还是菜鸟,我尝试使用我在网上找到的代码。

 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}

您似乎打开了 StorageFile 两次,这是不允许的。不要在调用 SaveVisualElementToFile 方法之前打开文件,因为您已经在该方法中打开了文件。

此外,您不需要 outstream.dispose,因为文件会在您的方法中使用 "using" 语句自动处理。