using System;
using System.ComponentModel;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
namespace WindowsFormsApplication1
{
static class NativeMethods
{
private static readonly IntPtr INVALID_HANDLE_VALUE = new IntPtr(-1);
private const uint FILE_READ_EA = 0x0008;
private const uint FILE_FLAG_BACKUP_SEMANTICS = 0x2000000;
[DllImport("Kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
private static extern uint GetFinalPathNameByHandle(IntPtr hFile, [MarshalAs(UnmanagedType.LPTStr)] StringBuilder filePath, uint length, uint flags);
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool CloseHandle(IntPtr hObject);
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern IntPtr CreateFile(
[MarshalAs(UnmanagedType.LPTStr)] string filename,
[MarshalAs(UnmanagedType.U4)] uint access,
[MarshalAs(UnmanagedType.U4)] FileShare share,
IntPtr securityAttributes, // optional SECURITY_ATTRIBUTES struct or IntPtr.Zero
[MarshalAs(UnmanagedType.U4)] FileMode creationDisposition,
[MarshalAs(UnmanagedType.U4)] uint flagsAndAttributes,
IntPtr templateFile);
///
/// Gibt von einem gemappten Verzeichnis das ursprüngliche Verzeichnis zurück.
/// Funktioniert beim System "C:\Dokumente und Einstellungen\All Users\LID\Data\"
/// und beim Server "P:\Themen\LID\".
///
/// das zu untersuchende Verzeichnis
/// das ursprüngliche Verzeichnis in der Notation des Systems
public static string GetFinalPathName(string path)
{
IntPtr h = NativeMethods.CreateFile(path,
NativeMethods.FILE_READ_EA,
FileShare.ReadWrite | FileShare.Delete,
IntPtr.Zero,
FileMode.Open,
NativeMethods.FILE_FLAG_BACKUP_SEMANTICS,
IntPtr.Zero);
if (h == NativeMethods.INVALID_HANDLE_VALUE)
{
// Pfad existiert nicht
throw new Win32Exception();
}
try
{
StringBuilder sb = new StringBuilder(1024);
uint res = NativeMethods.GetFinalPathNameByHandle(h, sb, 1024, 0);
if (res == 0)
{
throw new Win32Exception();
}
string finalPath = sb.ToString();
if (finalPath.StartsWith("\\\\?\\"))
{
return finalPath.Substring(4);
}
return finalPath;
}
finally
{
NativeMethods.CloseHandle(h);
}
}
}
}