gpt4 book ai didi

c# - 获取文件夹 ID C#

转载 作者:可可西里 更新时间:2023-11-01 13:34:30 24 4
gpt4 key购买 nike

我正在尝试跟踪文件和文件夹的整个生命周期(它们可能会被移动或重命名)。我已经完成搜索并发现 FileSystemWatcher可能是跟踪文件和文件夹的最流行的方式,但是,这对我不起作用,因为应用程序可能会或可能不会一直运行。我已选择尝试通过 ID 跟踪文件夹。

我找到了一种方法,可以根据 this stack post 的答案中的 ID 来跟踪文件.我可以根据 this answer 中的方法 B 成功获取文件 ID .

在搜索时我找到了 this stack post说他使用 FSCTL_GET_OBJECT_ID 找到了解决方案.我花了很多时间试图弄清楚如何使用此功能,但我无法全神贯注。我在 C# 中调用 native Windows 函数的经验基本上为零。

任何人都可以为此向正确的方向插入我吗?我觉得我一定错过了一些明显的东西。

是否存在 C# 无法访问文件/文件夹 ID 的原因?跟踪文件/文件夹是否不常见?

编辑,添加代码:

        static uint returnVal;

//Working example to get File ID
public static string GetFileId(string path)
{
WinAPI.BY_HANDLE_FILE_INFORMATION objectFileInfo = new WinAPI.BY_HANDLE_FILE_INFORMATION();

FileInfo fi = new FileInfo(path);
FileStream fs = fi.Open(FileMode.Open, FileAccess.Read, FileShare.ReadWrite);

WinAPI.GetFileInformationByHandle(fs.Handle, out objectFileInfo);

fs.Close();

ulong fileIndex = ((ulong)objectFileInfo.FileIndexHigh << 32) + (ulong)objectFileInfo.FileIndexLow;

return fileIndex.ToString();
}

public static string GetFolderId(string path)
{
//Get a handle on the given folder
IntPtr cFile = WinAPI.CreateFile(
path,
WinAPI.GENERIC_READ,
FileShare.Read,
IntPtr.Zero,
(FileMode)WinAPI.OPEN_EXISTING,
WinAPI.FILE_FLAG_BACKUP_SEMANTICS,
IntPtr.Zero);

Console.WriteLine(path);
Console.WriteLine(cFile);

if ((int)cFile != -1)
{
int cFileSize = Marshal.SizeOf(typeof(IntPtr));
Console.WriteLine("cFile size = {0}", cFileSize);

IntPtr cFileBlob = Marshal.AllocHGlobal(cFileSize);
uint numBytesRead = 0;

WinAPI.DeviceIoControl(cFile, WinAPI.FSCTL_GET_OBJECT_ID, IntPtr.Zero, 0, cFileBlob, (uint)cFileSize, ref numBytesRead, IntPtr.Zero);

if (returnVal == 0)
{
Console.WriteLine(Marshal.GetLastWin32Error()); // Returning error 87 here
}
}

//Should be returning the ID from the folder.
return String.Empty;
}

public static void Main(string[] args)
{
Console.WriteLine(GetFileId(@"C:\Users\Matt\Desktop\TestDocument.txt"));
Console.WriteLine(GetFolderId(@"C:\Users\Matt\Desktop"));
}

}

class WinAPI
{
// Win32 constants for accessing files.
internal const int GENERIC_READ = unchecked((int)0x80000000);
internal const int FILE_FLAG_BACKUP_SEMANTICS = unchecked((int)0x02000000);
internal const int OPEN_EXISTING = unchecked((int)3);
internal const int FSCTL_GET_OBJECT_ID = 0x0009009c;
internal const int FSCTL_CREATE_OR_GET_OBJECT_ID = 0x000900c0;

[DllImport("kernel32.dll", SetLastError = true)]
public static extern bool DeviceIoControl(IntPtr hDevice, uint dwIoControlCode, IntPtr lpInBuffer, uint nInBufferSize, [Out] IntPtr lpOutBuffer, uint nOutBufferSize, ref uint lpBytesReturned, IntPtr lpOverlapped);

[DllImport("kernel32.dll", SetLastError = true)]
public static extern bool GetFileInformationByHandle(IntPtr hFile, out BY_HANDLE_FILE_INFORMATION lpFileInformation);

[DllImport("kernel32.dll", SetLastError = true)]
public static extern IntPtr CreateFile(
String fileName,
int dwDesiredAccess,
System.IO.FileShare dwShareMode,
IntPtr securityAttrs_MustBeZero,
System.IO.FileMode dwCreationDisposition,
int dwFlagsAndAttributes,
IntPtr hTemplateFile_MustBeZero);

public struct BY_HANDLE_FILE_INFORMATION
{
public uint FileAttributes;
public FILETIME CreationTime;
public FILETIME LastAccessTime;
public FILETIME LastWriteTime;
public uint VolumeSerialNumber;
public uint FileSizeHigh;
public uint FileSizeLow;
public uint NumberOfLinks;
public uint FileIndexHigh;
public uint FileIndexLow;
}
}

我从 DeviceIoControl 收到错误“87”,根据 MSDN 上的帖子,这是无效参数(由于信誉限制,我无法发布更多链接。)

最佳答案

FileSystemWatcher 似乎没有问题。所以,关于如何在 C# 中使用 DeviceIoControl,请看这个答案:

Physical disk size not correct (IoCtlDiskGetDriveGeometry)

这道题,是用下面的代码完成的:

class Program {
const uint FSCTL_GET_OBJECT_ID=0x0009009c;

public static String GetFileId(String path) {
using(var fs=File.Open(
path,
FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite)
) {
WinAPI.BY_HANDLE_FILE_INFORMATION info;
WinAPI.GetFileInformationByHandle(fs.Handle, out info);
return String.Format(
"{0:x}", ((info.FileIndexHigh<<32)|info.FileIndexLow));
}
}

public static WinAPI.FILE_OBJECTID_BUFFER GetFolderIdBuffer(String path) {
using(var hFile=WinAPI.CreateFile(
path,
WinAPI.GENERIC_READ, FileShare.Read,
IntPtr.Zero,
(FileMode)WinAPI.OPEN_EXISTING,
WinAPI.FILE_FLAG_BACKUP_SEMANTICS,
IntPtr.Zero
)) {
if(null==hFile||hFile.IsInvalid)
throw new Win32Exception(Marshal.GetLastWin32Error());

var buffer=default(WinAPI.FILE_OBJECTID_BUFFER);
var nOutBufferSize=Marshal.SizeOf(buffer);
var lpOutBuffer=Marshal.AllocHGlobal(nOutBufferSize);
var lpBytesReturned=default(uint);

var result=
WinAPI.DeviceIoControl(
hFile, FSCTL_GET_OBJECT_ID,
IntPtr.Zero, 0,
lpOutBuffer, nOutBufferSize,
ref lpBytesReturned, IntPtr.Zero
);

if(!result)
throw new Win32Exception(Marshal.GetLastWin32Error());

var type=typeof(WinAPI.FILE_OBJECTID_BUFFER);

buffer=(WinAPI.FILE_OBJECTID_BUFFER)
Marshal.PtrToStructure(lpOutBuffer, type);

Marshal.FreeHGlobal(lpOutBuffer);
return buffer;
}
}

public static void Main(String[] args) {
Console.WriteLine(
GetFileId(@"C:\Users\Matt\Desktop\TestDocument.txt"));

var buffer=GetFolderIdBuffer(@"C:\Users\Matt\Desktop");

var objectId=buffer.ObjectId
.Reverse()
.Select(x => x.ToString("x2"))
.Aggregate(String.Concat);

Console.WriteLine("{0}", objectId);
}
}

class WinAPI {
internal const int
GENERIC_READ=unchecked((int)0x80000000),
FILE_FLAG_BACKUP_SEMANTICS=unchecked((int)0x02000000),
OPEN_EXISTING=unchecked((int)3);

[StructLayout(LayoutKind.Sequential)]
public struct FILE_OBJECTID_BUFFER {
public struct Union {
[MarshalAs(UnmanagedType.ByValArray, SizeConst=16)]
public byte[] BirthVolumeId;

[MarshalAs(UnmanagedType.ByValArray, SizeConst=16)]
public byte[] BirthObjectId;

[MarshalAs(UnmanagedType.ByValArray, SizeConst=16)]
public byte[] DomainId;
}

[MarshalAs(UnmanagedType.ByValArray, SizeConst=16)]
public byte[] ObjectId;

public Union BirthInfo;

[MarshalAs(UnmanagedType.ByValArray, SizeConst=48)]
public byte[] ExtendedInfo;
}

[StructLayout(LayoutKind.Sequential)]
public struct BY_HANDLE_FILE_INFORMATION {
public uint FileAttributes;
public FILETIME CreationTime;
public FILETIME LastAccessTime;
public FILETIME LastWriteTime;
public uint VolumeSerialNumber;
public uint FileSizeHigh;
public uint FileSizeLow;
public uint NumberOfLinks;
public uint FileIndexHigh;
public uint FileIndexLow;
}

[DllImport("kernel32.dll", SetLastError=true)]
public static extern bool DeviceIoControl(
SafeFileHandle hDevice,
uint dwIoControlCode,
IntPtr lpInBuffer,
uint nInBufferSize,
[Out] IntPtr lpOutBuffer,
int nOutBufferSize,
ref uint lpBytesReturned,
IntPtr lpOverlapped
);

[DllImport("kernel32.dll", SetLastError=true)]
public static extern SafeFileHandle CreateFile(
String fileName,
int dwDesiredAccess,
System.IO.FileShare dwShareMode,
IntPtr securityAttrs_MustBeZero,
System.IO.FileMode dwCreationDisposition,
int dwFlagsAndAttributes,
IntPtr hTemplateFile_MustBeZero
);

[DllImport("kernel32.dll", SetLastError=true)]
public static extern bool GetFileInformationByHandle(
IntPtr hFile, out BY_HANDLE_FILE_INFORMATION lpFileInformation);
}

namespace 需要使用:

using Microsoft.Win32.SafeHandles;

关于c# - 获取文件夹 ID C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16389383/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com