使用 C# System.IO.Path.Combine时需要注意的地方

本文介绍了一个用于路径组合的实用方法,解决了在使用路径时遇到的问题,即当路径中包含特定符号(如“/”)时,传统的路径组合方法可能会导致错误的结果。通过提供一种新的路径处理方法,可以有效地避免这些问题,并确保路径的正确组合。

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

说明,本人在使用过程中用了如下方法

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);

其中第二个后面的所有参数都不能带有 “/ 符号的路径,否则还是会返回path1的,如果需要支持路径的话。那么需要自己扩展一下该方法即可。。

        public static string CombinePath(this string path1, string path2)
        {
            if (string.IsNullOrEmpty(path2))
                return path1;
            var paths = path2.Split(new char[] { '\\', '/' });
            foreach (var item in paths.Select(s => s.Trim()).Where(s =>!string.IsNullOrEmpty( s)))
            {
                path1 = System.IO.Path.Combine(path1, item);
            }
            return path1;
        }

实用的在线工具 数学,圆周率,质数,合数,奇数,偶数,阶乘,约数,倍数,勾股数 域名由www.haomeili.net变为www.mz51.vip
      

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值