tags:

views:

73

answers:

4

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 can auto-detect the type of the address in the text box?

A: 

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.

Oded
A: 

Check Uri.HostNameType Property and Uri.Scheme Property

ArsenMkrt
This doesn't support UNC or local storage paths.
Oded
Unfortunately, you can't create a Uri instance for any paths that don't start with a "scheme" indentifier such as "http://" or "ftp://", or a drive letter; so "\\somecomputer", "someFile.htm" will all fail with a System.UriFormatException during construction of the Uri instance
Rob Levine
+2  A: 

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");
    }
}
Rob Levine
+1  A: 

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