2016-07-11 10 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

私の研究の後、こんにちは、私はシンリンクの実際のパスを取得する方法のこの解決策を見つけました。作成されたシンボリックリンクがあり、このファイルまたはフォルダの実際のポインタがどこにあるかチェックしたい場合。もし誰かがそれを書くよりよい方法を持っていれば、それを分けてください。

[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

'あなたは署名を 'private static extern int GetFinalPathNameByHandle([In] SafeFileHandle hFile、...')に変更できると思います。 –

関連する問題