3 Lösungen:
Im besten Fall, in dem Sie 100% sicher, dass der Anrufprozess vollen Zugriff auf das Dateisystem haben sind. CAVEAT: Erlaubnis auf einem Produktionsfeld kann
public static string PathCombineAndCanonicalize1(string path1, string path2)
{
string combined = Path.Combine(path1, path2);
combined = Path.GetFullPath(combined);
return combined;
}
Aber wir sind nicht immer frei schwierig sein. Oft müssen Sie die Zeichenfolgenarithmetik ohne Erlaubnis ausführen. Dafür gibt es einen nativen Anruf. CAVEAT: Resorts nativen Aufruf
public static string PathCombineAndCanonicalize2(string path1, string path2)
{
string combined = Path.Combine(path1, path2);
StringBuilder sb = new StringBuilder(Math.Max(260, 2 * combined.Length));
PathCanonicalize(sb, combined);
return sb.ToString();
}
[DllImport("shlwapi.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern bool PathCanonicalize([Out] StringBuilder dst, string src);
Eine dritte Strategie ist es, die CLR Trick. Path.GetFullPath() funktioniert gut auf einem fiktiven Pfad, also stellen Sie sicher, dass Sie immer einen geben. Was Sie tun können, ist die Wurzel mit einem falschen UNC-Pfad zu tauschen, ruft GetFullPath() und dann die wirkliche tauscht zurück in CAVEAT. dies eine schwer zu verkaufen in Code-Review erfordert
public static string PathCombineAndCanonicalize3(string path1, string path2)
{
string originalRoot = string.Empty;
if (Path.IsPathRooted(path1))
{
originalRoot = Path.GetPathRoot(path1);
path1 = path1.Substring(originalRoot.Length);
}
string fakeRoot = @"\\thiscantbe\real\";
string combined = Path.Combine(fakeRoot, path1, path2);
combined = Path.GetFullPath(combined);
combined = combined.Substring(fakeRoot.Length);
combined = Path.Combine(originalRoot, combined);
return combined;
}