Search code examples
c#wpfscreenshot

Saving Image to disk using Screenshot.Net library


hope everyone is doing well.

I am using the Screenshot.Net library to take an area drawn screenshots of a screen from a WPF application. The problem I am having is saving the screenshot to a directory within the project folder.

This is how the library currently saves the Image however it is not being stored to any directory:

public static BitmapSource ToBitmapSource(this Bitmap bitmap)
    {
        using (var stream = new MemoryStream())
        {
            bitmap.Save(stream, ImageFormat.Png);
            var bitmapImage = new BitmapImage();
            bitmapImage.BeginInit();
            bitmapImage.StreamSource = new MemoryStream(stream.ToArray());
            bitmapImage.EndInit();
            bitmapImage.Freeze();

            return bitmapImage;
        }
    }

I have tried specifying a directory save path but have so far been unable to get it to work. Any advice on how to proceed would be appreciated.


Solution

  • First, get a byte[] from the MemoryStream

    stream.Position = 0;
    byte[] imgBytes = stream.ToArray();
    

    Then, use built-in libs for writing.

    string basePath="<Your path without File name>";
    string fileName="<Your image name with extension>";
    System.IO.File.WriteAllBytes(Path.Combine(basePath, fileName), imgBytes);