Skip to content

Instantly share code, notes, and snippets.

@Paskowsky
Created June 11, 2020 10:33
Show Gist options
  • Save Paskowsky/52805b72c3f81a909db5c32558c6c551 to your computer and use it in GitHub Desktop.
Save Paskowsky/52805b72c3f81a909db5c32558c6c551 to your computer and use it in GitHub Desktop.
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
static class AntiRemove
{
const uint GENERIC_READ = 0x80000000;
const uint DUPLICATE_SAME_ACCESS = 0x00000002;
const uint FILE_SHARE_READ = 1;
const uint OPEN_EXISTING = 3;
public static bool LockFile(string filePath, params string[] processes)
{
IntPtr hCurrentProcess;
using (Process current = Process.GetCurrentProcess())
{
hCurrentProcess = current.Handle;
}
IntPtr hFile = CreateFile(filePath, GENERIC_READ, FILE_SHARE_READ, IntPtr.Zero, OPEN_EXISTING, 0, IntPtr.Zero);
if (hFile == IntPtr.Zero)
return false;
int count = 0;
foreach (Process p in Process.GetProcesses())
{
using (p)
{
try
{
if (processes.Length == 0 || Array.IndexOf(processes, p.ProcessName.ToLowerInvariant()) != -1)
{
Console.WriteLine("Locking with " + p);
IntPtr hFileClone;
IntPtr hProcess = p.Handle;
if (!DuplicateHandle(((IntPtr)(-1)), hFile, hProcess, out hFileClone, GENERIC_READ, false, DUPLICATE_SAME_ACCESS))
{
Marshal.ThrowExceptionForHR(Marshal.GetLastWin32Error());
}
count++;
}
}
catch
{
Console.WriteLine("Failed locking with " + p);
}
}
}
CloseHandle(hFile);
return count > 0;
}
[DllImport("kernel32", SetLastError = true)]
static extern bool CloseHandle(IntPtr hObject);
[DllImport("kernel32", SetLastError = true)]
static extern bool DuplicateHandle(IntPtr hSourceProcessHandle, IntPtr hSourceHandle, IntPtr hTargetProcessHandle, out IntPtr lpTargetHandle, uint dwDesiredAccess, bool bInheritHandle, uint dwOptions);
[DllImport("kernel32", SetLastError = true)]
static extern IntPtr CreateFile(string lpFileName, uint dwDesiredAccess,
uint dwShareMode, IntPtr lpSecurityAttributes, uint dwCreationDisposition,
uint dwFlagsAndAttributes, IntPtr hTemplateFile);
}
@nguyenthao1988
Copy link

How to unlock method when i locked this file.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment