代码之家  ›  专栏  ›  技术社区  ›  Serhat Ozgel

检测给定字符串的地址类型

  •  1
  • Serhat Ozgel  · 技术社区  · 16 年前

    我有一个文本框,允许用户在这些表单中输入地址:

    somefile.htm
    someFolder/somefile.htm
    c:\somepath\somemorepath\somefile.htm
    http://someaddress
    \\somecomputer\somepath\somefile.htm
    

    或任何其他导航到包含某些标记的内容的源。

    我是否应该在文本框附近放置一个下拉列表,询问这是什么类型的地址,或者是否有可靠的方法可以自动检测文本框中的地址类型?

    4 回复  |  直到 16 年前
        1
  •  3
  •   Rob Levine    16 年前

    我不认为有一种特别好的方法可以自动完成这项工作,而无需手工制作自己的检测。

    public string DetectScheme(string address)
    {
        Uri result;
        if (Uri.TryCreate(address, UriKind.Absolute, out result))
        {
            // You can only get Scheme property on an absolute Uri
            return result.Scheme;
        }
    
        try
        {
            new FileInfo(address);
            return "file";
        }
        catch
        {
            throw new ArgumentException("Unknown scheme supplied", "address");
        }
    }
    
        2
  •  1
  •   Jamie Altizer    16 年前

    我建议使用正则表达式来确定路径,类似于

      public enum FileType
      {
         Url,
         Unc,
         Drive,
         Other,
      }
      public static FileType DetermineType(string file)
      {
         System.Text.RegularExpressions.MatchCollection matches = System.Text.RegularExpressions.Regex.Matches(file, "^(?<unc>\\\\)|(?<drive>[a-zA-Z]:\\.*)|(?<url>http://).*$", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
         if (matches.Count > 0)
         {
            if (matches[0].Groups["unc"].Value == string.Empty) return FileType.Unc;
            if (matches[0].Groups["drive"].Value == string.Empty) return FileType.Drive;
            if (matches[0].Groups["url"].Value == string.Empty) return FileType.Url;
         }
         return FileType.Other;
      }
    
        3
  •  0
  •   Oded    16 年前

    如果格式的数量有限,则可以根据这些格式进行验证,并且只允许使用有效的格式。这将使自动检测更加容易,因为您将能够使用相同的逻辑进行检测。

    推荐文章