Justin808
Justin808

Reputation: 21512

c# ASP.NET How do i delete a file that is "in use" by another process?

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?

Upvotes: 1

Views: 3170

Answers (2)

Brian R. Bondy
Brian R. Bondy

Reputation: 347216

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");

Upvotes: 2

Martin Ongtangco
Martin Ongtangco

Reputation: 23505

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

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

Upvotes: 1

Related Questions