[英]Cannot write an image to a file using C#, due to an Unauthorized Access Exception
I have this code: 我有以下代码:
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);
}
It supposed to take a control from my XAML and create a "screenshot" of it and then save it to an image file. 它应该从我的XAML中获得一个控件,并为其创建一个“屏幕快照”,然后将其保存到图像文件中。 But no matter what directory I try to pass to the
File.Create
method, I get a System.UnauthorizedAccessException
. 但是,无论我尝试传递到
File.Create
方法的哪个目录,都会得到System.UnauthorizedAccessException
。
How to fix it? 如何解决? Thanks.
谢谢。
Note: I have tried to run Visual Studio as an administrator, didn't work. 注意:我试图以管理员身份运行Visual Studio,但没有用。
You'll have to pass a file name (optionally including a path) to File.Create
, like: 您必须将文件名(可选地包括路径)传递给
File.Create
,例如:
File.Create("MyImage.png")
or 要么
var path = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.MyPictures), "MyImage.png");
using (var fileStream = FileFile.Create(path))
{
pngImage.Save(fileStream);
}
To get rid of the black image try manually disposing the object after you've used it. 要消除黑色图像,请尝试在使用完该对象后手动对其进行处理。 Example shown below.
示例如下所示。
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();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.