c# - 在 UWP 中保存图像时访问被拒绝。访问被拒绝。 (HRESULT : 0x80070005 (E_ACCESSDENIED)) 的异常

标签 c# uwp windows-10-universal uwp-xaml win2d

我正在 Windows 10 SDK 上开发通用 Windows 应用程序,以便在图像中识别的面部上绘制矩形。

我正在使用Win2D编辑图片并在其上绘制矩形。我可以从图片库中读取文件,但是当我尝试在编辑后保存图像时,会出现以下错误:

Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))

以下是我在图像上绘制矩形的方法:

private async void DrawRect()
    {
        CanvasDevice device = CanvasDevice.GetSharedDevice();
        CanvasBitmap bitmap = null;
        CanvasRenderTarget offscreen = null;

        Windows.Storage.StorageFile photofile = await KnownFolders.PicturesLibrary.GetFileAsync("image.jpg");

        if(photofile != null)
        {
            using (var stream = await photofile.OpenReadAsync())
            {
                bitmap = await CanvasBitmap.LoadAsync(device, stream);
            }
        }

        if(bitmap != null)
        {
            offscreen = new CanvasRenderTarget(device, bitmap.SizeInPixels.Width, bitmap.SizeInPixels.Height, 96);
            using (var ds = offscreen.CreateDrawingSession())
            {
                ds.Clear(Colors.Transparent);
                ds.DrawImage(bitmap);
                ds.DrawRectangle(25, 35, 270, 352, Colors.Blue,4);
            }

            var photoFile = await KnownFolders.PicturesLibrary.CreateFileAsync("image2.jpg", CreationCollisionOption.ReplaceExisting);                        

            if (photofile != null)
            {
                await offscreen.SaveAsync(photofile.Path);
            }              

            //await offscreen.SaveAsync(photoFile.Path);*/
        }
    }

在最后一行 offscreen.SaveAsync 处抛出异常。

上述错误的堆栈跟踪是:

at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Runtime.CompilerServices.TaskAwaiter.GetResult() at IdentifyFacesApp.IdentifiedFaces.d__5.MoveNext()

我已经在appmanifest文件中设置了访问图片文件夹的权限。

我是否需要设置一些额外的权限才能将图像保存在磁盘中。

当我尝试将图像保存在任何其他位置时,也会发生同样的错误。

最佳答案

尝试通过流而不是路径访问文件:

var photoFile = await KnownFolders.PicturesLibrary.CreateFileAsync("image2.jpg", CreationCollisionOption.ReplaceExisting);

if (photofile != null)
{
    using (var stream = await photofile.OpenAsync(FileAccessMode.ReadWrite))
    {
        await offscreen.SaveAsync(stream, CanvasBitmapFileFormat.Jpeg);
    }
}

在 UWP 中,如果您通过路径访问文件,在许多情况下您可能会遇到访问被拒绝的情况,应该通过StorageFile来完成。

关于c# - 在 UWP 中保存图像时访问被拒绝。访问被拒绝。 (HRESULT : 0x80070005 (E_ACCESSDENIED)) 的异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42599136/

相关文章:

c# - XNA 是否提供音频输入(线路输入)?

c# - C# .NET 中任意长的 Parallel.For 循环

.net - DataTemplate 中的 TemplateBinding 不起作用

c# - UWP - TextBox 在 Windows 10 build 14393 中缺少换行符 (\n)

visual-studio-2015 - 是否需要多个版本的 Windows SDK?

C# uwp 应用程序防止空闲模式

C# 如何在 OAuth 重定向后保留 session 或 Cookie 信息?

c# - 在代码中绑定(bind)到 DependencyProperty

c# - UWP/C# 关于存储应用程序用户数据的建议?

c# - Windows 10 中的 Html 编辑类似于邮件应用程序?