2016-07-11 87 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,...' –