【问题标题】:Cannot write an image to a file using C#, due to an Unauthorized Access Exception由于未经授权的访问异常,无法使用 C# 将图像写入文件
【发布时间】:2016-08-06 04:25:08
【问题描述】:

我有这个代码:

RenderTargetBitmap renderTargetBitmap = new RenderTargetBitmap(525, 50, 96, 96, PixelFormats.Pbgra32);
renderTargetBitmap.Render(/* controlName */);
PngBitmapEncoder pngImage = new PngBitmapEncoder();
pngImage.Frames.Add(BitmapFrame.Create(renderTargetBitmap));
using (Stream fileStream = File.Create(Environment.CurrentDirectory)
{
    pngImage.Save(fileStream);
}

它应该从我的 XAML 中获取控制并创建它的“屏幕截图”,然后将其保存到图像文件中。但是无论我尝试将哪个目录传递给File.Create 方法,我都会得到一个System.UnauthorizedAccessException

如何解决?谢谢。

注意:我曾尝试以管理员身份运行 Visual Studio,但没有成功。

【问题讨论】:

  • 您的应用程序没有访问该目录的权限。确保您写入的位置是运行您的应用程序的帐户具有写入权限的位置。
  • 错误的完整堆栈跟踪是什么?您是否也尝试过使用File.WriteAllBytes(); 方法?尝试将其保存到您登录用户的桌面。
  • @WicherVisser- 我尝试了几个位置,包括“C:”驱动器、桌面以及应用程序本身的目录。
  • @Wjdavis5 - 你能详细说明一下吗?非常感谢你们!
  • @Sipo 详细说明了哪一部分?您可能无法保存到 C 驱动器根目录。但是桌面应该可以正常工作。

标签: c# wpf xaml


【解决方案1】:

您必须将文件名(可选地包括路径)传递给File.Create,例如:

File.Create("MyImage.png")

var path = Path.Combine(
    Environment.GetFolderPath(Environment.SpecialFolder.MyPictures), "MyImage.png");

using (var fileStream = FileFile.Create(path))
{
    pngImage.Save(fileStream);
}

【讨论】:

  • 是的。它完美地工作。谢谢。问题是它会创建黑色图像。知道为什么吗?
  • 渲染控件是动态创建的,还是已经显示在 UI 中的某个位置?
  • 它是在运行时在后面的代码中创建的。在阅读您的评论后,我尝试将元素更改为在 XAML 中创建的元素,并且它有效 - 但我尝试“动态”创建的元素没有。
  • 您必须在控件上调用 Measure 和 Arrange 才能执行其初始布局。参见例如这里:stackoverflow.com/a/12766990/1136211 或这里:stackoverflow.com/a/28628256/1136211
  • 嗯,请您在答案中解释如何使用这些Measure and Arrange人员?我对这一切都很陌生...非常感谢您的帮助!
【解决方案2】:

要消除黑色图像,请尝试在使用对象后手动处理它。示例如下。

private void button_Click(object sender, RoutedEventArgs e)
    {
        RenderTargetBitmap renderTargetBitmap = new RenderTargetBitmap(525, 50, 96, 96, PixelFormats.Pbgra32);
        renderTargetBitmap.Render(btn_StartStop);
        PngBitmapEncoder pngImage = new PngBitmapEncoder();
        pngImage.Frames.Add(BitmapFrame.Create(renderTargetBitmap));
        FileStream stream = new FileStream("screenshot.png", FileMode.Create);
        pngImage.Save(stream);
        stream.Dispose();            
    } 

【讨论】:

  • 这相当于using 块,其中using 是首选方法。
  • @Clemens 完全理解,其中一些成像方法在 using 块内时无法正确渲染图像。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-07-01
  • 1970-01-01
  • 2018-08-21
  • 1970-01-01
  • 1970-01-01
  • 2021-03-05
  • 2021-12-03
相关资源
最近更新 更多