Skip to content

Instantly share code, notes, and snippets.

@joncloud
Created May 11, 2018 02:19
Show Gist options
  • Select an option

  • Save joncloud/9ba628152c1794df612bc7244567f226 to your computer and use it in GitHub Desktop.

Select an option

Save joncloud/9ba628152c1794df612bc7244567f226 to your computer and use it in GitHub Desktop.
using Meziantou.Framework.Win32;
using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Management;
using System.Threading;
using System.Threading.Tasks;
namespace ConsoleApp53
{
class Program
{
static void Main(string[] args) =>
MainAsync().GetAwaiter().GetResult();
static async Task MainAsync()
{
var source = new CancellationTokenSource();
var task = LockFile("C:/temp/test.txt", source.Token);
Console.ReadLine();
// Meziantou.Framework.Win32.RestartManager
using (var manager = RestartManager.CreateSession())
{
manager.RegisterFile("C:/temp/test.txt");
foreach (var process in manager.GetProcessesLockingResources())
{
Console.Write(process.Id);
Console.Write("\t");
Console.Write(process.ProcessName);
Console.Write(" ");
Console.WriteLine(process.GetCommandLine());
}
}
Console.ReadLine();
source.Cancel();
await task;
}
static Task LockFile(string file, CancellationToken cancellationToken)
{
return Task.Run(
() =>
{
using (var stream = new FileStream(file, FileMode.Open, FileAccess.ReadWrite, FileShare.None))
{
cancellationToken.WaitHandle.WaitOne();
}
},
cancellationToken
);
}
}
static class ProcessExtensions
{
public static string GetCommandLine(this Process process)
{
// System.Management
using (var searcher = new ManagementObjectSearcher("SELECT CommandLine FROM Win32_Process WHERE ProcessId = " + process.Id))
using (var objects = searcher.Get())
{
return objects.Cast<ManagementBaseObject>().SingleOrDefault()?["CommandLine"]?.ToString();
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment