【问题标题】:Normalizing file paths规范化文件路径
【发布时间】:2014-06-18 13:14:39
【问题描述】:

我需要规范化一个文件路径,以便可以通过String.StartsWith(...)匹配路径的一部分

例子:

  • 完整路径:C:/Common/Dir1/Dir2/file.txt
  • CommonPath:C:\Common\

虽然这两个文件路径是等价的,但是公共部分不能通过String.StartsWith(...)方法匹配。

我现在知道 API 方法:Path.NormalizePath(path, true); 可以做规范化,但不幸的是这个方法是internal protected

为了使文件路径标准化,我还有哪些其他机会? Path.GetFullPath(...) 可能是可选的,但仅适用于绝对文件路径,因为它会为相对路径添加一个前缀,例如:C:/

【问题讨论】:

    标签: .net c#-2.0


    【解决方案1】:

    .net 2.0 下的这项工作

    using System;
    using System.Collections.Generic;
    using System.Text;
    
    namespace ConsoleApplication1
    {
        class Program
        {
            static void Main(string[] args)
            {
                var path = @"C:/Common/Dir1/Dir2/file.txt";
                var canonicalPath = new Uri(path).LocalPath;
    
                Console.WriteLine(canonicalPath.StartsWith(@"C:\Common\"));
    
                Console.Read();
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2016-11-10
      • 2010-10-15
      • 2010-09-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-17
      • 2017-06-04
      • 2015-03-25
      相关资源
      最近更新 更多