How do I find out which process is locking a file using .NET?

前端 未结 6 1024
渐次进展
渐次进展 2020-11-22 00:42

I\'ve seen several of answers about using Handle or Process Monitor, but I would like to be able to find out in my own code (C#) which process is locking a file.

I ha

6条回答
  •  春和景丽
    2020-11-22 01:03

    simpler with linq:

    public void KillProcessesAssociatedToFile(string file)
        {
            GetProcessesAssociatedToFile(file).ForEach(x =>
            {
                x.Kill();
                x.WaitForExit(10000);
            });
        }
    
        public List GetProcessesAssociatedToFile(string file)
        {
            return Process.GetProcesses()
                .Where(x => !x.HasExited
                    && x.Modules.Cast().ToList()
                        .Exists(y => y.FileName.ToLowerInvariant() == file.ToLowerInvariant())
                    ).ToList();
        }
    

提交回复
热议问题