thealbinosmurf
thealbinosmurf

Reputation: 561

How to overcome writing over a file C#

EDIT: Add method where error actually occurs...

I am opening an image and I want to be able to overwrite the original file as modification happens. I tryed both of the methods here

public ImgPro(String Path)
{
    Bitmap bt1 = new Bitmap(Path);
    Bitmap bt2 = new Bitmap(bt1.Width, bt1.Height, PixelFormat.Format24bppRgb);
    var imgRec = new Rectangle(0, 0, bt1.Width, bt1.Height);
    Graphics bt2G = Graphics.FromImage(bt2);
    bt2G.DrawImage(bt1, imgRec);
    bt1.Dispose();
    this.bitmap = bt2;
}

And

public ImgPro(String Path)
{
    Bitmap bt1 = new Bitmap(Path);
    Bitmap bt2 = new Bitmap(bt1.Width, bt1.Height, PixelFormat.Format24bppRgb);
    var imgRec = new Rectangle(0, 0, bt1.Width, bt1.Height);
    BitmapData bt1Data = bt1.LockBits(imgRec, ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);
    BitmapData bt2Data = bt2.LockBits(imgRec, ImageLockMode.WriteOnly, PixelFormat.Format24bppRgb);

    // Create data array to hold bmpSource pixel data
    int numBytes = bt1Data.Stride * (int)bt1.Height;
    var srcData = new byte[numBytes];
    var destData = new byte[numBytes];

    Marshal.Copy(bt1Data.Scan0, srcData, 0, numBytes);
    Array.Copy(srcData, destData, srcData.Length);
    Marshal.Copy(destData, 0, bt2Data.Scan0, numBytes);

    bt1.UnlockBits(bt1Data); bt2.UnlockBits(bt2Data);
    bt1.Dispose();
    this.bitmap = bt2;
}

But both options failed when I went to save the file I got this error.

An unhandled exception of type 'System.Runtime.InteropServices.ExternalException' occurred in System.Drawing.dll

For this method:

public void Save(string filename)
{
     bitmap.Save(filename, ImageFormat.Jpeg);
}

Upvotes: 0

Views: 93

Answers (1)

Jacob
Jacob

Reputation: 78920

Since Bitmap locks the underlying stream, you could copy the file contents to a MemoryStream and base the Bitmap on that instead. This should prevent the file from being locked:

var bytes = File.ReadAllBytes(Path);
using (var stream = new MemoryStream(bytes)) // Don't dispose this until you're done with your Bitmap 
{
    Bitmap bt1 = new Bitmap(stream);
    // ...
}

Upvotes: 1

Related Questions