Here is the code that I use to close my application, its associated processes and to delete all the files that have been extracted during the use of the application:
private void Quit_Click(object sender, RoutedEventArgs e) //close the application
{
//kill cinector after all import is done
Process[] processes = Process.GetProcesses();
for (int i = 0; i < processes.Count(); i++)
{
if (processes[i].ProcessName.ToLower().Contains("CinectorProcess"))
{
processes[i].Kill();
}
}
//also kill powerpoint just in case
for (int i = 0; i < processes.Count(); i++)
{
if (processes[i].ProcessName.ToLower().Contains("powerpnt"))
{
processes[i].Kill();
}
}
//kill the engine
ShutdownEngine();
//kill the main app
App.Current.Shutdown();
//also delete all three folders
//slides_png_prev
if (Directory.Exists(slides_png_prev))
{
Thumbnails = null;
Directory.Delete(slides_png_prev, true);
}
//slides_png
if (Directory.Exists(slides_png))
{
Directory.Delete(slides_png, true);
}
//slides_png_prev_seleect
if (Directory.Exists(slides_png_prev_seleect))
{
Directory.Delete(slides_png_prev_seleect, true);
}
}
However, the problem is that when it tries to delete the files (which are the images used somewhere in the app) it shows the following exception:
"The process cannot access the file because it is being used by another process."
Update:
I found that the process 'Mastersolution.vhost.exe' is holding all the files that I am attempting to delete. Mastersolution is actually the main app that I am closing on the line App.Current.Shutdown();
So I need to somehow disconnect the files from the main application prior to deleting them. But hoe to do this?
Store your files in a temp directory and let the operating system handle it.
See Path.GetTempPath and Path.GetTempFileName.
First you should determine, which file in the folder is locked - instead of deleting whole folder, delete individual files. Then check with Process Explorer and Ctrl+F what process really uses the undeletable file.
Also you can use the method WhoIsLocking
in this code.
https://bitbucket.org/snippets/wiip/nnGX
You can use it to determine, which process locks the file. Then you can write something like this to kill this process automatically:
List<Process> lp = FileUtil.WhoIsLocking(fileName);
foreach (Process p in lp)
{
p.Kill();
}
This is last workaround when there are no better options, like closing the file in your app, closing Powerpoint using automation etc.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With