C#中的Path.Combine()方法可以用来将多个路径部分组合成一个路径。
使用方法
Path.Combine()方法接受任意多个参数,每个参数可以是一个字符串,也可以是一个字符串数组,它们将被合并成一个路径。例如:
string path1 = Path.Combine("C:\\", "Program Files", "MyApp"); string path2 = Path.Combine("C:\\", new string[] {"Program Files", "MyApp"}); // path1和path2的值都是C:\Program Files\MyApp
如果参数中有任何一个是null,那么Path.Combine()将会抛出一个ArgumentNullException异常,如果参数中任何一个是空字符串,那么Path.Combine()将会忽略它们。
示例
下面是一个使用Path.Combine()方法组合多个路径的示例:
string path1 = @"C:\Program Files\MyApp"; string path2 = @"C:\Program Files\MyApp\Images"; string combinedPath = Path.Combine(path1, path2); //combinedPath的值为C:\Program Files\MyApp\Images
Path.Combine()方法非常有用,它可以帮助我们快速组合多个路径。