I think intially you need to know whether the file is in use and if not you can .
delete it.
Add this function which returns whether the file is in open.
public static bool IsFileInUse(string pathToFile)
{
if (!System.IO.File.Exists(pathToFile))
{
return false;
}
bool inUse = false;
System.IO.FileStream fs;
try
{
fs = System.IO.File.Open(pathToFile, System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.Read, System.IO.FileShare.None);
fs.Close();
DirectoryInfo di = new DirectoryInfo(pathToFile));
FileInfo[] fi = di.GetFiles();
foreach (FileInfo f in fi)
{
f.Delete();
}
}
catch (System.IO.IOException ex)
{
string exMess = ex.Message;
inUse = true;
}
return inUse;
}
If the file is in open and if you know the process name which it takes in task manager you can forcefully delete the process which releases the files.
Code for killing that particular process.
Here I've taken Acrobat reader as the process which opens the PDF files.
public void KillProcess()
{
try
{
foreach (Process process in Process.GetProcesses())
{
if (process.ProcessName == "AcroRd32")
{
process.Kill();
}
}
}
catch (Exception exception)
{
}
}