2

I have a test.log file, and I want to edit that programmatically.

string text = File.ReadAllText("test.log");
text = text.Replace("xxx", "yyy");
File.WriteAllText("test.log", text);

But I receive the error "file is in use by another process."

How can I find the process using this file to kill it?

I used this code Process.GetProcesses(), but that was a long list without any helpful information. Also, this file generated from a dll and I don't have access to its code.

I also cannot use a third party program such as lockhunter or handel.exe for this purpose.

Negar
  • 866
  • 2
  • 10
  • 20
  • http://stackoverflow.com/questions/317071/how-do-i-find-out-which-process-is-locking-a-file-using-net – OldProgrammer Apr 23 '17 at 17:56
  • 2
    Maybe it is better to find out _why_ some process locks your log file and fix the real issue instead of just killing some random process? – Evk Apr 23 '17 at 17:59
  • Just as a side note: log files are usually meant to be append-only. You shouldn't really change it, but process it or change the way it's generated – Jordão Apr 23 '17 at 18:00
  • Possible duplicate of [How do I find out which process is locking a file using .NET?](http://stackoverflow.com/questions/317071/how-do-i-find-out-which-process-is-locking-a-file-using-net) – Chris Apr 23 '17 at 18:02

1 Answers1

1

Are you looking for something like this:

public static List<Process> GetProcessesLockingFile(string filePath)
{
    var procs = new List<Process>();

    var processListSnapshot = Process.GetProcesses();
    foreach (var process in processListSnapshot)
    {
        Console.WriteLine( process.ProcessName);
        if (process.Id <= 4) { continue; } // system processes
        var files = GetFilesLockedBy(process);
        if (files.Contains(filePath))
        {               
            Console.WriteLine("--------------->" + process.ProcessName);
            procs.Add(process);
        }
    }

    return procs;
}

Following is a link which will help you. This looks like the exact question that is used here:

https://www.codeproject.com/questions/531409/fileplusisplususedplusbyplusanotherplusprocessplus
Biswabid
  • 1,378
  • 11
  • 26
  • 1
    Which library/namespace does `GetFilesLockedBy` belong to? – Bojan Komazec Apr 23 '17 at 18:01
  • 2
    Never mind, I found it. Your code is very similar to the one here: http://stackoverflow.com/questions/860656/using-c-how-does-one-figure-out-what-process-locked-a-file. It is always better to provide here full implementation of any non-standard method you use (the one which is not in .NET or in some 3rd party library). – Bojan Komazec Apr 23 '17 at 18:06