tags:

views:

39

answers:

4
  private void save(Rectangle src, Rectangle dest, string fName, int width, int height, Bitmap file)
        {
            Bitmap result = new Bitmap(width, height);

            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.

+3  A: 

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.

m0sa
+2  A: 

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.

binarycoder
It could possibly be Vista/Windows 7 search indexing the file. As noted, a process cannot hold a lock on a file after the process is terminated.
Josh Einstein
+1  A: 

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)

Aaronaught
A: 

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

Ageis