简体   繁体   中英

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?

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM