文件路径处理之Path.ChangeExtension

我最近在用开源GIS组件SharpMap做开发时候,经常要处理这样的问题:比如现在已获得Shapefile主文件(*.shp)的文件路径如"F:\\China400\\Sdzzd_P.shp",然后要根据它获取其索引文件(*.shx)和dDASE表文件(*.dbf)的文件路径,之前我一直采用自己编写的方法来处理这个字符串,直到刚刚查阅MSDN的时间才发现之前的方法是多么愚蠢,其实微软已经为开发人员做好了这一切,在.NET中,System.IO.Path.ChangeExtension方法即可很方便的处理这个问题。

示例

using System.IO;
class Program
{
    static void Main()
    {
        // The file name.
        string path = "test.txt";
        // Make sure the file exists.
        File.WriteAllText(path, "Tutorial file");
        // Change the path name to have a new extension in memory.
        string changed = Path.ChangeExtension(path, ".html");
        // Create file with the new extension name.
        File.WriteAllText(changed, "Changed file");
    }
}

在示例代码string changed = Path.ChangeExtension(path, ".html")中,用“.html”后缀来替换“.txt”后缀,一定不要忘了前置的点符号。

除此之外,还可以利用该方法来移除文件路径字符串中的后缀部分,见如下示例。

using System;
using System.IO;
class Program
{
    static void Main()
    {
        string original = "file.txt";
        Console.WriteLine(Path.ChangeExtension(original, ""));      //output: file.
        Console.WriteLine(Path.ChangeExtension(original, null));    //output: file
    }
}

注意用空字符串和null分别作参数时其结果的差异,用null做参数将移除整个后缀,而用空字符串做参数则只移除后缀字符,但仍保留了点符号。

MSDN真是一份大宝库,还得时时去发掘!

posted @ 2012-06-07 17:35  百折不回  阅读(1481)  评论(0编辑  收藏  举报