如何克服写入文件C#

时间:2013-12-12 00:50:59

标签: c#

编辑:添加实际发生错误的方法......

我正在打开图像,我希望能够在修改发生时覆盖原始文件。我尝试了两种方法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;
}

并且

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

但是当我去保存文件时,两个选项都失败了。我得到了这个错误。

  

System.Drawing.dll中出现未处理的“System.Runtime.InteropServices.ExternalException”类型异常

对于这种方法:

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

1 个答案:

答案 0 :(得分:1)

由于Bitmap锁定了基础流,您可以将文件内容复制到MemoryStream,然后将Bitmap置于其上。这应该可以防止文件被锁定:

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