Forcing closed an open file by C#

2019-02-12 08:54发布

问题:

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?

回答1:

First you can use this post to verify that it's the dodgy app that's locking them:

How do I find out which process is locking a file using .NET?

Then this post outlines a way to close them:

http://social.msdn.microsoft.com/Forums/en-US/csharplanguage/thread/04a1e899-2a38-4d95-8ed5-6d53344e4d76



回答2:

This is probably irrelevant and if it is please someone comment but there was a work-around I've used in explorer before to get around file locks.
If a file was locked by a process that had died Windows often wouldn't let you delete it but if you created a new file of the same name somewhere else, moved it to the folder it would succeed. You could then delete the new file and all was well.
To use this for your app you'd have to be able to read the file and hold it in memory before you did this then you write it back out after you'd got rid of the old one.
Maybe it will help, maybe not but it's worth trying.



回答3:

    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;
        }
    }