文件路径处理之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真是一份大宝库,还得时时去发掘!

转载于:https://www.cnblogs.com/hans_gis/archive/2012/06/07/2540634.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值