gpt4 book ai didi

c# - 从符号链接(symbolic link) C# 获取真实路径

转载 作者:太空狗 更新时间:2023-10-30 01:32:07 25 4
gpt4 key购买 nike

有谁知道如何从符号链接(symbolic link)文件或文件夹中获取真实路径?谢谢!

最佳答案

大家好,经过我的研究,我找到了这个关于如何获取符号链接(symbolic link)的真实路径的解决方案。如果你有一个创建的符号链接(symbolic link)并想检查这个文件或文件夹的真正指针在哪里。如果有人有更好的写法请分享。

    [DllImport("kernel32.dll", EntryPoint = "CreateFileW", CharSet = CharSet.Unicode, SetLastError = true)]
private static extern SafeFileHandle CreateFile(string lpFileName, int dwDesiredAccess, int dwShareMode, IntPtr securityAttributes, int dwCreationDisposition, int dwFlagsAndAttributes, IntPtr hTemplateFile);

[DllImport("kernel32.dll", EntryPoint = "GetFinalPathNameByHandleW", CharSet = CharSet.Unicode, SetLastError = true)]
private static extern int GetFinalPathNameByHandle([In] SafeFileHandle hFile, [Out] StringBuilder lpszFilePath, [In] int cchFilePath, [In] int dwFlags);

private const int CREATION_DISPOSITION_OPEN_EXISTING = 3;
private const int FILE_FLAG_BACKUP_SEMANTICS = 0x02000000;


public static string GetRealPath(string path)
{
if (!Directory.Exists(path) && !File.Exists(path))
{
throw new IOException("Path not found");
}

SafeFileHandle directoryHandle = CreateFile(path, 0, 2, IntPtr.Zero, CREATION_DISPOSITION_OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, IntPtr.Zero); //Handle file / folder

if (directoryHandle.IsInvalid)
{
throw new Win32Exception(Marshal.GetLastWin32Error());
}

StringBuilder result = new StringBuilder(512);
int mResult = GetFinalPathNameByHandle(directoryHandle, result, result.Capacity, 0);

if (mResult < 0)
{
throw new Win32Exception(Marshal.GetLastWin32Error());
}

if (result.Length >= 4 && result[0] == '\\' && result[1] == '\\' && result[2] == '?' && result[3] == '\\')
{
return result.ToString().Substring(4); // "\\?\" remove
}
return result.ToString();
}

关于c# - 从符号链接(symbolic link) C# 获取真实路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38299901/

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