c# Path.Combine

本文详细介绍了C#中Path.Combine方法的工作原理和常见应用场景,包括如何处理相对路径、驱动器路径和HTTP链接等问题,并通过实例展示了其潜在的错误用法。Path.Combine虽然简化了路径拼接,但在某些情况下可能无法得到预期结果,如处理相对路径时会忽略第一个路径,与HTTP路径不兼容等。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Path.Combine:

c#获取当前项目路径 :

 1 //获取包含当前执行的代码的程序集的加载文件的完整路径
 2             var appPath = System.IO.Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
 3             Console.WriteLine(appPath);
 4 
 5             //获取模块的完整路径
 6             string path = System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName;
 7             Console.WriteLine(path);
 8 
 9             //获取和设置当前目录(该进程从中启动的目录)的完全限定目录。
10             var dicPath = System.Environment.CurrentDirectory;
11             Console.WriteLine(dicPath);
12 
13             //获取程序的基目录
14             string basePath = System.AppDomain.CurrentDomain.BaseDirectory;
15             Console.WriteLine(basePath);
16 
17             //获取和设置包括该应用程序的目录的名称
18             string domainPath = System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
19             Console.WriteLine(domainPath);

输出结果:

 

 

 

System.IO.Path.Combine 简单来说,就是合并两个及两个以上的路径字符串。

 

 1             //两个都是绝对路径,返回后者
 2             string tmp = Path.Combine(@"C:\user", @"D:\test.txt");
 3             Console.WriteLine(tmp);
 4             //如果指定的路径之一是零长度字符串,则该方法返回其他路径。
 5             //当然,两个都是零长度字符串,则返回的就是 string.Empty ;
 6             string tmp1 = Path.Combine("", @"D:\test.txt");
 7             Console.WriteLine(tmp1);
 8             string tmp2 = Path.Combine(@"C:\user", "");
 9             Console.WriteLine(tmp2);
10             //如果其中一个参数为 null ,会抛出异常(System.ArgumentNullException)
11             string tmp3 = Path.Combine(@"C:\user", null);
12             Console.WriteLine(tmp3);

 

输出结果:

 

所以下面的代码可以完美的工作:

public static void Main()

{

    string[] arr_pa = { @"c:\abc\", @"c:\abc" };

    string[] arr_pb = { @"test.txt" };

    foreach (string pa in arr_pa)

    {

        foreach (string pb in arr_pb)

        {

            Console.WriteLine("'{0}' + '{1}'= '{2}'", pa, pb, Path.Combine(pa, pb));

        }

    }

}

结果如下:

 

 

从这个例子可以知道,我们不需要考虑arr_pa里面的字符串是不是以”\” 结尾,这的确提供了方便,而且这也是很多人喜欢使用Path.Combine的一个原因,但是仅此而已。

 

Path.Combine 虽然解决了路径连接问题,但是由于很多人片面的去理解它,所有它非常容易造成错误的应用,要想用好Path.Combine 并非易事,下面我会列举几个实例来说明这点。

 

第一个:当path2 是相对路径的时候,返回的是path2,path1会被丢弃。

看一下下面的代码:

public static void Main()

{

    string[] arr_pa = { @"c:\abc\", @"c:\abc" };

    string[] arr_pb = { @"\test.txt", @"/test.txt", @"test.txt" };

 

    foreach (string pa in arr_pa)

    {

        foreach (string pb in arr_pb)

        {

            Console.WriteLine("'{0}' + '{1}'= '{2}'", pa, pb, Path.Combine(pa, pb));

        }

    }

}

你知道这段代码输出什么吗?

这段代码的输出如下:

 

可以看到对于”/test.txt” 和”\test.txt” ,Path.Combine 认为path2是相对路径,所以直接返回path2.。

第二点:路径是驱动器,返回的结果不正确

public static void Main()

{

    string[] arr_pa = { @"c:", @"c:\" };

    string[] arr_pb = { @"\test.txt", @"/test.txt", @"test.txt" };

 

    foreach (string pa in arr_pa)

    {

        foreach (string pb in arr_pb)

        {

            Console.WriteLine("'{0}' + '{1}'= '{2}'", pa, pb, Path.Combine(pa, pb));

        }

    }

}

输出结果是:

 

可以看到,如果path1 是” C:”的话,那么Path.Combine结果就是不正确的。

第三点:无法连接http路径

除了连接本地路路径之外,有的时候,也需要拼接http链接地址,可惜的是System.IO.Path.Combine却无法拼接http地址。

将arr_pa 修改为

string[] arr_pa = { @"http://www.Test.com/", @"http://www.Test.com" };

结果如下:

 

在这里就没有什么技巧了,纯粹的死记硬背,

 

public static string Combine(string path1, string path2);

public static string Combine(string path1, string path2, string path3);

public static string Combine(string path1, string path2, string path3, string path4);

其中第二个后面的所有参数都不能带有 “/” 符号的路径,否则还是会返回最后一个能组成的相对路径的。

 

1  string[] arr_pa = { @"c:\abc\", @"c:\abc" };
2             string[] arr_pb = { @"\test.txt", @"/test.txt", @"test.txt" };
3             foreach (string pa in arr_pa)
4             {
5                 foreach (string pb in arr_pb)
6                 {
7                     Console.WriteLine("'{0}' + '{1}'= '{2}'", pa, pb, Path.Combine(pa,"/users", pb));
8                 }
9             }

 

输出如下:

 

如果需要支持路径的话。那么需要自己扩展一下该方法即可。。

 1 public static string CombinePath(this string path1, string path2)
 2 {
 3 if (string.IsNullOrEmpty(path2))
 4 return path1;
 5 var paths = path2.Split(new char[] { '\\', '/' });
 6 foreach (var item in paths.Select(s => s.Trim()).Where(s =>!string.IsNullOrEmpty( s)))
 7 {
 8 path1 = System.IO.Path.Combine(path1, item);
 9 }
10 return path1;
11 }

输出结果:

 

 

但是还是不能解决Url地址的问题

正是因为上述的几点不足,导致Path.Combine 很难用,这也是有一部分人选择使用String.Format 的原因了。

转载于:https://www.cnblogs.com/likui-bookHouse/p/11084685.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值