System.IO.Path.Combine(string path1, string path2)
kann zwei Pfad-Segmente miteinander verbinden und kümmert sich auch ordentlich drum, wenn path1 (nicht) mit einem Backslash endet.
Hier ist ein Code-Schnipsel, der es erlaubt beliebig viele Segmente hintereinander zu schalten.
private static String GetPath(params String[] pathSegments)
{
if ((pathSegments != null) && (pathSegments.Length > 0))
{
var path = Environment.ExpandEnvironmentVariables(pathSegments[0]);
for (var i = 1; i < pathSegments.Length; i++)
{
var expanded = Environment.ExpandEnvironmentVariables(pathSegments[i]);
path = Path.Combine(path, expanded);
}
return (path);
}
return (null);
}
private static void ShowPath(params String[] pathSegments)
{
var path = GetPath(pathSegments);
if (String.IsNullOrEmpty(path) == false)
{
Console.WriteLine(path);
Console.WriteLine(Directory.Exists(path));
var di = new DirectoryInfo(path);
Console.WriteLine(di.FullName);
Console.WriteLine(Directory.Exists(di.FullName));
path = GetPath(path, "csc.exe");
Console.WriteLine(path);
Console.WriteLine(File.Exists(path));
var fi = new FileInfo(path);
Console.WriteLine(fi.FullName);
Console.WriteLine(File.Exists(fi.FullName));
}
Console.WriteLine();
}
static void Main()
{
ShowPath();
ShowPath(null);
ShowPath(@"C:\");
ShowPath(@"C:\", "Windows", "Microsoft.NET", "Framework", "v2.0.50727");
ShowPath(@"C:\Windows\Microsoft.NET\Framework", "v2.0.50727");
ShowPath(@"C:\Windows\Microsoft.NET", @"Framework\v2.0.50727");
ShowPath(@"C:\Windows\Microsoft.NET\", @"Framework\v2.0.50727");
ShowPath(@"C:\Windows\Microsoft.NET\..\", @"Microsoft.NET\Framework\v2.0.50727");
ShowPath("%WinDir%", @"Microsoft.NET\Framework\v2.0.50727");
Console.ReadLine();
}
3 Kommentare zum Snippet