2016-07-11 60 views
4

有人知道如何从符号链接文件或文件夹中获得真正的路径吗?谢谢!从符号链接获取真正的路径C#

+1

请将此重写为一个问题,并[将解决方案作为答案](http://stackoverflow.com/help/self-answer)。 – Martheen

+0

谢谢@Martheen,获取这些信息! –

+0

似乎是重复http://stackoverflow.com/questions/2302416/in-net-how-to-obtain-the-target-of-a-symbolic-link-or-reparse-point – qbik

回答

3

大家好我的研究后,我发现这个解决方案如何获得Symlink的真正路径。如果你有一个创建的符号链接,并想检查这个文件或文件夹的真实指针在哪里。如果有人有更好的写作方式,请分享。

[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] IntPtr 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"); 
     } 

     DirectoryInfo symlink = new DirectoryInfo(path);// No matter if it's a file or folder 
     SafeFileHandle directoryHandle = CreateFile(symlink.FullName, 0, 2, System.IntPtr.Zero, CREATION_DISPOSITION_OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, System.IntPtr.Zero); //Handle file/folder 

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

     StringBuilder result = new StringBuilder(512); 
     int mResult = GetFinalPathNameByHandle(directoryHandle.DangerousGetHandle(), 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 
     } 
     else 
     { 
      return result.ToString(); 
     } 
    } 
+0

而不是做' directoryHandle.DangerousGetHandle()'我认为你可以将签名改为'private static extern int GetFinalPathNameByHandle([In] SafeFileHandle hFile,...' –