Check if the path input is URL or Local File

Just using new Uri(yourPath) won't work in all cases.

Comparing various scenarios (via LinqPad).

    var tests = new[] {
        Path.GetTempFileName(),
        Path.GetDirectoryName(Path.GetTempFileName()),
        "http://in.ter.net",
        "http://in.ter.net/",
        "http://in.ter.net/subfolder/",
        "http://in.ter.net/subfolder/filenoext",
        "http://in.ter.net/subfolder/file.ext",
        "http://in.ter.net/subfolder/file.ext?somequerystring=yes",
        Path.GetFileName(Path.GetTempFileName()),
        Path.Combine("subfolder", Path.GetFileName(Path.GetTempFileName())),
    };

    tests.Select(test => {
        Uri u;
        try {
            u = new Uri(test);
        } catch(Exception ex) {
            return new {
                test,
                IsAbsoluteUri = false,
                // just assume
                IsFile = true,
            };
        }

        return new {
            test,
            u.IsAbsoluteUri,
            u.IsFile,
        };
    }).Dump();

Results

Linqpad results of path checking


private static bool IsLocalPath(string p)
{
  return new Uri(p).IsFile;
}

...or, if you want to include support for certain invalid URIs...

private static bool IsLocalPath(string p)
{
  if (p.StartsWith("http:\\"))
  {
    return false;
  }

  return new Uri(p).IsFile;
}

Example Usage

static void Main(string[] args)
{
  CheckIfIsLocalPath("C:\\foo.txt");
  CheckIfIsLocalPath("C:\\");
  CheckIfIsLocalPath("http://www.txt.com");
}

private static void CheckIfIsLocalPath(string p)
{
  var result = IsLocalPath(p); ;

  Console.WriteLine("{0}  {1}  {2}", result, p, new Uri(p).AbsolutePath);
}

Tags:

C#