2009-12-24 18 views
1

我有一个文本框,允许哪些用户在这些表单中输入地址:检测地址类型给出的字符串

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

或导航到一些内容,包含一些标记,任何其他来源。

我应该也把一个下拉附近的文本框列表,问什么类型的地址是这样的,或者是有可以自动检测在文本框中输入地址的类型的可靠途径?

回答

3

我不认为有自动做这个没有起草自己的检测特别好的方式。

如果你不介意在故障情况下捕获异常(我一般),然后下面的代码片段会为你的例子(注意,这也将确定目录为类型的文件)

工作
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"); 
    } 
} 
0

如果只有格式的数量有限,你可以验证针对这些,只允许有效的。这将使自动检测更容易一些,因为您可以使用相同的逻辑。

0
+0

这并不支持UNC或本地存储路径。 – Oded 2009-12-24 09:57:16

+1

不幸的是,您不能为任何不以“http://”或“ftp://”或驱动器号等“scheme”标识符开头的路径创建Uri实例;所以在构造Uri实例期间,“\\ somecomputer”,“someFile.htm”都将失败,并显示System.UriFormatException – 2009-12-24 09:57:46

1

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

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; 
    }