开发者

How to kill a C# process?

I am building a C# program that unzips a file, and work on this file.

Sometimes I get this m开发者_运维技巧essage: "the process cannot access the file c:.... because it is being used by another process"

What I can do? How to kill it?


You have to find out which program that is accessing the file. Have you forgotten to exit one of your own applications, or are there any other accessing the file?

You can write C# code to kill a process, but a better approach would be to find out why it is already being used by another process.

To kill all processes with name nameOfProcess in C#:

Process[] ps = Process.GetProcessesByName("nameOfProcess");

foreach (Process p in ps)
    p.Kill();

Also, as @Darin notes, you could take a look at this other SO thread: How do I find out which process is locking a file using .NET?

The sysinternals tools that is mentioned by @Darin in the comments is found at http://technet.microsoft.com/en-us/sysinternals/bb896645.aspx


Process Monitor will work but Process Explorer is a much better application for this. It is also from Sysinternals which is now owned by Microsoft. Run Process Explorer as an administrator and then click the search button. This will then show applications and threads that are using the file.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜