<p>I'm looking for a way to delete a file which is locked by another process using C#. I suspect the method must be able to find which process is locking the file (perhaps by tracking the handles, although I'm not sure how to do this in C#) then close that process before being able to complete the file delete using <code>File.Delete()</code>.</p>

You can use this program,
Handle
, to find which process has the lock on your file. It's a command-line tool, so I guess you use the output from that. I'm not sure about finding it programmatically.
If deleting the file can wait, you could specify it for deletion when your computer next starts up:
Start
```
REGEDT32 (W2K)
```
or
```
REGEDIT (WXP)
```
and navigate to:
```
```
HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Session Manager
```
```
W2K and WXP
W2K:
Edit
Add Value...
Data Type:
```
REG_MULTI_SZ
```
Value Name:
```
PendingFileRenameOperations
```
OK
WXP:
Edit
New
Multi-String Value
enter
```
PendingFileRenameOperations
```
In the Data area, enter
```
"\??\" + filename
```
to be deleted. LFNs may
be entered without being embedded in quotes. To delete
```
C:\Long Directory Name\Long File Name.exe
```
, enter the following data:
```
```
\??\C:\Long Directory Name\Long File Name.exe
```
```
Then press
OK
.
The "destination file name" is a null (zero) string. It is entered
as follows:
W2K:
Edit
Binary
select Data Format: Hex
click at the end of the hex string
enter 0000 (four zeros)
OK
WXP:
Right-click the value
choose "Modify Binary Data"
click at the end of the hex string
enter 0000 (four zeros)
OK
Close
```
REGEDT32/REGEDIT
```
and reboot to delete the file.
(Shamelessly stolen from
some random forum
, for posterity's sake.)