我一直致力于一个项目,在这个项目中,软件只需要删除40,000多个文件目录中其他地方(硬链接)链接的文件。我已经使用以下功能取得了一些成功:
[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)]
static extern bool GetFileInformationByHandle(SafeFileHandle handle, out BY_HANDLE_FILE_INFORMATION lpFileInformation);
[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
static extern SafeFileHandle CreateFile(
string lpFileName,
[MarshalAs(UnmanagedType.U4)] FileAccess dwDesiredAccess,
[MarshalAs(UnmanagedType.U4)] FileShare dwShareMode,
IntPtr lpSecurityAttributes,
[MarshalAs(UnmanagedType.U4)] FileMode dwCreationDisposition,
[MarshalAs(UnmanagedType.U4)] FileAttributes dwFlagsAndAttributes,
IntPtr hTemplateFile);
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool CloseHandle(SafeHandle hObject);
public static int GetFileLinkCount(string filepath)
{
try
{
int result = 0;
SafeFileHandle handle = CreateFile(filepath, FileAccess.Read, FileShare.Read, IntPtr.Zero, FileMode.Open, FileAttributes.Archive, IntPtr.Zero);
BY_HANDLE_FILE_INFORMATION fileInfo = new BY_HANDLE_FILE_INFORMATION();
if (GetFileInformationByHandle(handle, out fileInfo))
result = (int)fileInfo.NumberOfLinks;
CloseHandle(handle);
return result;
}
catch { return 1; }
}
当我致电GetFileLinkCount
时,我得到了我想要的东西(值> 1确认该文件是硬链接。)。但是,当我遍历目录中的所有文件夹并继续调用GetFileLinkCount
时,程序进入中断模式并抛出System.Runtime.InteropServices.SEHException: 'External component has thrown an exception.'
,这对我的调试没有帮助。这就是我所说的:
string[] paths = Directory.GetFiles("E:\\P3D", "*", SearchOption.AllDirectories);
for(int i = 0; i < paths.Length; i++)
{
if (GetFileLinkCount(paths[i]) > 1)
{
File.Delete(paths[i]);
}
}
几秒钟后,应用程序崩溃并出现上述异常。这很奇怪,因为有些硬链接被删除了,但有些硬链接没有被删除,因为应用程序在完成循环之前崩溃了。任何帮助将不胜感激!