C# PInvoke 我无法使用 CreateFile 打开卷
C# PInvoke I can't open the volume with CreateFile
我必须使用 PInvoke 中的 CreateFile 打开卷:
[DllImport("kernel32.dll", SetLastError = true)]
static extern SafeFileHandle CreateFile(string lpFileName, uint dwDesiredAccess, FileShare dwShareMode, IntPtr securityAttrs, FileMode dwCreationDisposition, FileOptions dwFlagsAndAttributes, IntPtr hTemplateFile);
但是当我使用它时:
var fileName = @"C:\Users\myuser\Desktop\file.txt"
var root = Path.GetPathRoot(fileName);
var volumePath = @"\.\" + root.Substring(0, root.Length - 1);
var volume = CreateFile(volumePath, GENERIC_READ, FileShare.Read, IntPtr.Zero, FileMode.Open, FileOptions.None, IntPtr.Zero);
if (volume.IsInvalid)
throw new Win32Exception(Marshal.GetLastWin32Error());
它打印:
Access is denied
但是,如果我以提升的权限打开它,它会打印:
The process cannot access the file because it is being used by another process
我一直在尝试一切,甚至从很多地方获取代码,但我无法让它工作。
使用取自 here 的 PInvoke 代码:
var volume = CreateFile(volumePath, EFileAccess.GenericRead, EFileShare.Read|EFileShare.Write, IntPtr.Zero, ECreationDisposition.OpenExisting, 0, IntPtr.Zero);
我已经成功运行了。
我必须使用 PInvoke 中的 CreateFile 打开卷:
[DllImport("kernel32.dll", SetLastError = true)]
static extern SafeFileHandle CreateFile(string lpFileName, uint dwDesiredAccess, FileShare dwShareMode, IntPtr securityAttrs, FileMode dwCreationDisposition, FileOptions dwFlagsAndAttributes, IntPtr hTemplateFile);
但是当我使用它时:
var fileName = @"C:\Users\myuser\Desktop\file.txt"
var root = Path.GetPathRoot(fileName);
var volumePath = @"\.\" + root.Substring(0, root.Length - 1);
var volume = CreateFile(volumePath, GENERIC_READ, FileShare.Read, IntPtr.Zero, FileMode.Open, FileOptions.None, IntPtr.Zero);
if (volume.IsInvalid)
throw new Win32Exception(Marshal.GetLastWin32Error());
它打印:
Access is denied
但是,如果我以提升的权限打开它,它会打印:
The process cannot access the file because it is being used by another process
我一直在尝试一切,甚至从很多地方获取代码,但我无法让它工作。
使用取自 here 的 PInvoke 代码:
var volume = CreateFile(volumePath, EFileAccess.GenericRead, EFileShare.Read|EFileShare.Write, IntPtr.Zero, ECreationDisposition.OpenExisting, 0, IntPtr.Zero);
我已经成功运行了。