开发者

my program keeps hold of files it's written using GDI+

开发者 https://www.devze.com 2022-12-22 08:57 出处:网络
private void save(Rectangle src, Rectangle dest, string fName, int width, int height, Bitmap file) { Bitmap result = new Bitmap(width, height);
  private void save(Rectangle src, Rectangle dest, string fName, int width, int height, Bitmap file)
        {
            Bitmap result = new Bitmap(width, height);

       开发者_Go百科     Graphics g = Graphics.FromImage(result);

            g.DrawImage(file, dest, src, GraphicsUnit.Pixel);
            result.Save(fName);

            g.Dispose();
            result.Dispose();
            result = null;
            g = null;

        }

It does write the files but for some reason even if the program is closed, it keeps hold of them.


Try to use the overload with a Stream as a parameter of the Bitmap.Save() method. Then you can dispose the FileStream you pass as the argument.


It does write the files but for some reason even if the program is closed, it keeps hold of them.

Not possible. The operating system closes all files when the process exits. Must be some other process that has the file open.

Use the Process Explorer (http://technet.microsoft.com/en-us/sysinternals/bb896653.aspx) Find, Find Handle menu command on the file name to determine the process.


First of all, stop setting variable references to null - that has no significant effect in .NET. The garbage collector decides when to free memory after variables go out of scope.

Second, you're not handling exceptions properly here. C# gives you the try and using constructs for a reason: use them.

using (Bitmap result = new Bitmap(width, height))
{
    using (Graphics g = Graphics.FromImage(result))
    {
        g.DrawImage(file, dest, src, GraphicsUnit.Pixel);
    }
    result.Save(fName);
}

This code is a lot easier to read and won't leak resources if something unexpected happens.

If you're finding that the file itself is still locked or that GDI resources are still leaking, then something else is responsible - the above code cannot leak resources nor keep a file locked. (Except in the event of certain fatal exceptions, but in that case your whole program is going down anyway)


Thanks to everyone. According to process explorer it was some ps3 controller software I was using and also nokia pc suite.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号