tags:

views:

64

answers:

2

I'm loading a file:

System.Drawing.Image img = System.Drawing.Image.FromFile(FilePath);

Now I would like to save the image:

img.Save(SavePath);

This works.. Unless FilePath == SavePath, then it decides to give me the error:

System.Runtime.InteropServices.ExternalException: A generic error occurred in GDI+.

So I tried to delete the file, right after opening it:

System.Drawing.Image img = System.Drawing.Image.FromFile(FilePath);
File.Delete(FilePath);

And it gives me the error:

System.IO.IOException: The process cannot access the file 'filename.jpg' because it is being used by another process.

So... How can I modify an existing file, that's "in use" when its not in use by anyone?

+1  A: 

you can either use Memory stream or put it in byte[] array

http://www.vcskicks.com/image-to-byte.php

Martin Ongtangco
This page helped a lot.
Justin808
@Justin808 if it helped you should up vote it.
Sayed Ibrahim Hashimi
glad i've helped.
Martin Ongtangco
+2  A: 

The image will remain locked until it is disposed (See here).

The file remains locked until the Image is disposed.

You'll have to save the image somewhere else (or copy its contents out) and then dispose the opened image via using a using clause.

Example:

using(Image image1 = Image.FromFile("c:\\test.jpg"))
{
    image1.Save("c:\\test2.jpg");
}

System.IO.File.Delete("c:\\test.jpg");
System.IO.File.Move("c:\\test2.jpg", "c:\\test.jpg");
Brian R. Bondy
Why in heavens name would the file stay locked? its opened, read into memory, and closed? makes the Image type a PITA.
Justin808
@Justin808: I'm not sure in the reasoning but the documentation says so by design, see my edit above.
Brian R. Bondy
This works, but the link below explains how to do this without the use of a temporary file.
Justin808