zoukankan      html  css  js  c++  java
  • 文件路径处理之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真是一份大宝库,还得时时去发掘!

  • 相关阅读:
    Symbol《ES6标准入门(第3版)》
    理解对象《JavaScript高级程序设计》
    创建对象《JavaScript高级程序设计》
    对象的新增方法《ES6标准入门(第3版)》
    继承《JavaScript高级程序设计》
    操作符《JavaScript高级程序设计》
    作用域闭包《你不知道的JavaScript(上)》
    【浏览器】相关知识
    iOS深色模式媒体查询css
    阿里云OSS前端直传
  • 原文地址:https://www.cnblogs.com/hans_gis/p/2540634.html
Copyright © 2011-2022 走看看