【问题标题】:.NET2 Test if a string is a valid path [duplicate].NET2 测试字符串是否为有效路径 [重复]
【发布时间】:2013-01-24 09:26:25
【问题描述】:

Path.IsPathRooted() 这样的.NET 方法很棒,但如果输入字符串无效则抛出。这很好,但是在跳转到异常检查代码块之前预先检查输入字符串是否是有效路径会很好。

我看不到Path.IsValidPath() 或类似的,有类似的东西吗?

【问题讨论】:

  • 在“路径存在”或“路径符合正式标准”中是否有效?
  • 有效,因为它会使用Path 方法抛出异常:)
  • @Ani 我不认为这是同一个问题 - 例如,某些有效的 URI 肯定会导致 Path.IsRooted() 中的异常?

标签: .net .net-2.0


【解决方案1】:

您可以使用File.ExistsDirectory.Exists

如果您想检查路径是否包含非法字符(在 NET 2.0 上),您可以使用 Path.GetInvalidPathChars:

char[] invalidChars = System.IO.Path.GetInvalidPathChars();
bool valid = path.IndexOfAny(invalidChars) != -1;

【讨论】:

    【解决方案2】:
    public bool ValidPathString(string path)
    {
        if (string.IsNullOrEmpty(path)) return false;
        char[] invalidPathChars = System.IO.Path.GetInvalidPathChars();
        foreach (char c in invalidPathChars)
        {
            if(path.Contains(c)) return false;
        }
        return true;
    }
    

    【讨论】:

      【解决方案3】:

      根据文档,

      ArgumentException [当] path 包含 GetInvalidPathChars 中定义的一个或多个无效字符时抛出。

      这意味着您可以按如下方式预先验证您的路径字符串:

      if (path.IndexOfAny(Path.GetInvalidPathChars()) != -1) {
          // This means that Path.IsPathRooted will throw an exception
          ....
      }
      

      这是IsPathRooted 引发异常的唯一条件。

      查看Mono source of Path.cs,第 496 行,了解如何实现的详细信息。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-11-12
        • 2011-01-13
        • 2014-06-16
        • 2016-05-04
        • 2013-08-05
        • 2021-07-11
        • 2018-08-10
        • 1970-01-01
        相关资源
        最近更新 更多