基于为何我不喜欢用Path.Combine的详解

所属分类: 软件编程 / C#教程 阅读数: 157
收藏 0 赞 0 分享

Path.Combine:

image

什么时候会用到Path.Combine呢?,当然是连接路径字符串的时候!

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

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

        }

    }

}

结果如下:

image

当然你也可以:

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

结果是:

image

从这个例子可以知道,我们不需要考虑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));

        }

    }

}

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

这段代码的输出如下:

image

可以看到对于”/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));

        }

    }

}

输出结果是:

image

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

第三点:无法连接http路径

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

arr_pa 修改为

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

结果如下:

image

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

记住,只有

image

才会产生正确的解。

如果你将代码修改为:

public static void Main()

{

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

    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, "def", pb));

        }

    }

}

那么无论怎样,你都无法得到正确的结果:

image

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

当然,我写了一个MyPath.Combine的方法,可以解决上面的问题。

复制代码 代码如下:

class MyPath
    {
        public static string Combine(params string[] paths)
        {
            if (paths.Length == 0)
            {
                throw new ArgumentException("please input path");
            }
            else
            {
                StringBuilder builder = new StringBuilder();
                string spliter = "\\";

                string firstPath = paths[0];

                if (firstPath.StartsWith("HTTP", StringComparison.OrdinalIgnoreCase))
                {
                    spliter = "/";
                }

                if (!firstPath.EndsWith(spliter))
                {
                    firstPath = firstPath + spliter;
                }
                builder.Append(firstPath);

                for (int i = 1; i < paths.Length; i++)
                {
                    string nextPath = paths[i];
                    if (nextPath.StartsWith("/") || nextPath.StartsWith("\\"))
                    {
                        nextPath = nextPath.Substring(1);
                    }

                    if (i != paths.Length - 1)//not the last one
                    {
                        if (nextPath.EndsWith("/") || nextPath.EndsWith("\\"))
                        {
                            nextPath = nextPath.Substring(0, nextPath.Length - 1) + spliter;
                        }
                        else
                        {
                            nextPath = nextPath + spliter;
                        }
                    }

                    builder.Append(nextPath);
                }

                return builder.ToString();
            }
        }
    }


使用也比较简单

例如:

public static void Main()

{

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

    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, MyPath.Combine(pa, pb));

        }

    }

}

结果如下:

image

当然,你也可以这样:

Console.WriteLine("{0}+{1}+{2}+{3}={4}",

                        pa, "p2", "\\p3/", pb, MyPath.Combine(pa, "p2", "\\p3/", pb));

输出如下:

image

最后如果你不用Path.Combine,那么还可以选择string.Format

更多精彩内容其他人还在看

c#开发word批量转pdf源码分享

已经安装有Office环境,借助一些简单的代码即可实现批量Word转PDF,看下面的实例源码吧
收藏 0 赞 0 分享

c# xml API操作的小例子

这篇文章主要介绍了c# xml API操作的小例子,有需要的朋友可以参考一下
收藏 0 赞 0 分享

c#唯一值渲染实例代码

这篇文章主要介绍了c#唯一值渲染实例代码,有需要的朋友可以参考一下
收藏 0 赞 0 分享

淘宝IP地址库采集器c#代码

这篇文章主要介绍了淘宝IP地址库采集器c#代码,有需要的朋友可以参考一下
收藏 0 赞 0 分享

C#在后台运行操作(BackgroundWorker用法)示例分享

BackgroundWorker类允许在单独的专用线程上运行操作。如果需要能进行响应的用户界面,而且面临与这类操作相关的长时间延迟,则可以使用BackgroundWorker类方便地解决问题,下面看示例
收藏 0 赞 0 分享

c#文本加密程序代码示例

这是一个加密软件,但只限于文本加密,加了窗口控件的滑动效果,详细看下面的代码
收藏 0 赞 0 分享

c#生成站点地图(SiteMapPath)文件示例程序

这篇文章主要介绍了c#生成站点地图(SiteMapPath)文件的示例,大家参考使用
收藏 0 赞 0 分享

C# 键盘Enter键取代Tab键实现代码

这篇文章主要介绍了C# 键盘Enter键取代Tab键实现代码,有需要的朋友可以参考一下
收藏 0 赞 0 分享

C# WinForm导出Excel方法介绍

在.NET应用中,导出Excel是很常见的需求,导出Excel报表大致有以下三种方式:Office PIA,文件流和NPOI开源库,本文只介绍前两种方式
收藏 0 赞 0 分享

C#串口通信程序实例详解

在.NET平台下创建C#串口通信程序,.NET 2.0提供了串口通信的功能,其命名空间是System.IO.Ports,创建C#串口通信程序的具体实现是如何的呢?让我们开始吧
收藏 0 赞 0 分享
查看更多