7

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?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Gold
  • 60,526
  • 100
  • 215
  • 315

2 Answers2

13

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

Community
  • 1
  • 1
csl
  • 10,937
  • 5
  • 57
  • 89
  • 2
    To find out at first who is locking your file, you should take a look into ProcessMonitor from sysinternals. Just click on the spyglass in the toolbar and enter the name of your file. You get a list of all processes which have an open handle to this file. – Oliver Oct 29 '09 at 08:25
2

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.

Paxamime
  • 203
  • 2
  • 7