Forcing closed an open file by C#

Viewed 29632

I found a similar question here but it was closed/accepted with an answer of "don't do that".

I'm in a situation where I don't care what happens to the other applications, I want to take a file that may be locked by others (rudely if needed) and have my way with it. I may need to move, rename, or delete this file.

Basically I need to process files in a directory that is created by an app that doesn't clean up it's locks. I know the app is done processing when mine calls, but I need to kill the locks when I run. In addition it seems I'm conflicting with reads from local AV software scanning the remote share where the server is.

All this adds up to an unresolvable "force close" situation so I can do what I need. Does anyone have an idea on what to do?

3 Answers
    foreach (var process in Process.GetProcessesByName("excel")) //whatever you need to close 
    {
        if (process.MainWindowTitle.Contains("test.xlsx"))
        {
            process.Kill();
            break;
        }
    }

or

    foreach (var process in Process.GetProcesses())
    {
        if (process.MainWindowTitle.Contains("test.dat"))
        {
            process.Kill();
            break;
        }
    }
Related