Michael Haddad
Michael Haddad

Reputation: 4435

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. But no matter what directory I try to pass to the File.Create method, I get a System.UnauthorizedAccessException.

How to fix it? Thanks.

Note: I have tried to run Visual Studio as an administrator, didn't work.

Upvotes: 0

Views: 244

Answers (2)

Clemens
Clemens

Reputation: 128042

You'll have to pass a file name (optionally including a path) to File.Create, like:

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);
}

Upvotes: 2

Cuken
Cuken

Reputation: 29

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();            
    } 

Upvotes: -1

Related Questions