I have a text box, which users are allowed to enter addresses in these forms:
somefile.htm
someFolder/somefile.htm
c:\somepath\somemorepath\somefile.htm
http://someaddress
\\somecomputer\somepath\somefile.htm
or any other source that navigates to some content, containing some markup.
Should I also put a drop down list near the text box, asking what type of address is this, or is there a reliable way that ca开发者_StackOverflow社区n auto-detect the type of the address in the text box?
I don't think there is a particularly nice way of automatically doing this without crafting your own detection.
If you don't mind catching an exception in the failure case (which generally I do), then the snippet below will work for your examples (noting that it will also identify directories as being of type file)
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");
}
}
I would suggest using a regex to determine the paths, similar to
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;
}
If there is only a limited number of formats, you can validate against these and only allow valid ones. This will make auto-detection a bit easier as you will be able to use the same logic for that.
Check Uri.HostNameType Property and Uri.Scheme Property
精彩评论