Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete a file being used by another process

I'm trying to programmically delete a file, but the file is apparently being used by another process (which happens to be my program). Basically, the program loads images from a folder by using FromUri to create a Bitmap, which is then loaded into an Image array, which in turn becomes the child of a stackpanel. Not very efficient, but it works.

I've tried clearing the stackpanel's children, and making the images in the array null, but I'm still getting the IOException telling me that the file is being used by another process.

Is there some other way to remove the file from my application's processes?

like image 289
bramco Avatar asked Nov 07 '12 03:11

bramco


People also ask

How do you delete a file that is used by another process in Java?

Method available in every Java versionFile filePath = new File( "SomeFileToDelete. txt" ); boolean success = filePath. delete();

How do you force delete a folder that is being used?

Use “RMDIR /S /Q” command to force delete a folder in CMD: After entering Command Prompt window, you can type the rmdir /s /q folder path, for example, rmdir /s /q E:\test, and press Enter key. This deletes the folder named “test” in my USB drive.


2 Answers

it may be Garbage Collection issue.

System.GC.Collect();  System.GC.WaitForPendingFinalizers();  File.Delete(picturePath); 
like image 172
kplshrm7 Avatar answered Oct 14 '22 09:10

kplshrm7


In order to release an image file after loading, you have to create your images by setting the BitmapCacheOption.OnLoad flag. One way to do this would be this:

string filename = ... BitmapImage image = new BitmapImage(); image.BeginInit(); image.CacheOption = BitmapCacheOption.OnLoad; image.UriSource = new Uri(filename); image.EndInit(); 

Although setting BitmapCacheOption.OnLoad works on a BitmapImage that is loaded from a local file Uri, this is afaik nowhere documented. Therefore a probably better or safer way is to load the image from a FileStream, by setting the StreamSource property instead of UriSource:

string filename = ... BitmapImage image = new BitmapImage();  using (var stream = File.OpenRead(filename)) {     image.BeginInit();     image.CacheOption = BitmapCacheOption.OnLoad;     image.StreamSource = stream;     image.EndInit(); } 
like image 32
Clemens Avatar answered Oct 14 '22 10:10

Clemens