kartal
kartal

Reputation: 18086

Delete file when it used in another process

In DocumentViewerControl in WPF I want to delete the file after closing the control in closed event handler. I tried to delete it but VS told me that it is used by another process. How can I delete it?

TextBlock tb = (TextBlock)e.TabItem.Header;
int index = Convert.ToInt32(tb.Text.Split(' ')[1]) - 2;
string path = GlobalStaticVariables.store_item_content[index].Split('-')[1];
Process temp = Process.GetCurrentProcess();
temp.Dispose();
System.IO.File.Delete(path);

Upvotes: 2

Views: 2013

Answers (1)

Alexei Levenkov
Alexei Levenkov

Reputation: 100527

This question is asked many times by now and answer still does not change: deleting files opened by other processes is bad and as result made hard to do. Usually it is better to figure out why file is locked and either fix application behavior to avoid extensive file locking or wait till application releases the file.

To investigate who locks the file you can use Handle or GUI version - Process Explorer by Microsoft/SysInternals.

See related messages to discussions on this topic.

Upvotes: 4

Related Questions