Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to kill a C# process?

Tags:

c#

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

Sometimes I get this message: "the process cannot access the file c:.... because it is being used by another process"

What I can do? How to kill it?

like image 897
Gold Avatar asked Oct 29 '09 08:10

Gold


2 Answers

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

like image 63
csl Avatar answered Sep 21 '22 03:09

csl


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.

like image 34
Paxamime Avatar answered Sep 23 '22 03:09

Paxamime