Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Physical, Relative, Absolute and other paths

Tags:

c#

.net

path

uri

unc

I have a task to write an object that can receive a different type of paths/urls, and return what type of path/url it is. For example the path can be

1. [drive]:\Temp 
2. \\Temp 
3. Temp (assuming that it relative Temp), 
4. /Temp 
5. ~/Temp 
6. file://[drive]:/Temp 
7. file://Temp 
8. [scheme]://something/Temp

...and so on.

How I can check in C# if it's physical path, relative url, or absolute url?

I think it's relatively easy to know if it's relative or absolute uri, but how to know if it's UNC path?

I tried to use Uri object and it's IsUnc property, but it not really helps me....for c:\temp it returns false, for "/temp", "temp/" and "temp" it throws an exception that format is incorrect. Does exists any built in object in .NET 3.5 that can help me with this, or what algorithm i can use to determine the type of path?

like image 898
Alex Dn Avatar asked Nov 01 '12 12:11

Alex Dn


1 Answers

Try this:

var paths = new[]
{
   @"C:\Temp",
   @"\\Temp",
   "Temp",
   "/Temp",
   "~/Temp",
   "file://C:/Temp",
   "file://Temp",
   "http://something/Temp"
};

foreach (string p in paths)
{
   Uri uri;
   if (!Uri.TryCreate(p, UriKind.RelativeOrAbsolute, out uri))
   {
      Console.WriteLine("'{0}' is not a valid URI", p);
   }
   else if (!uri.IsAbsoluteUri)
   {
      Console.WriteLine("'{0}' is a relative URI", p);
   }
   else if (uri.IsFile)
   {
      if (uri.IsUnc)
      {
         Console.WriteLine("'{0}' is a UNC path", p);
      }
      else
      {
         Console.WriteLine("'{0}' is a file URI", p);
      }
   }
   else
   {
      Console.WriteLine("'{0}' is an absolute URI", p);
   }
}

Output:

'C:\Temp' is a file URI
'\\Temp' is a UNC path
'Temp' is a relative URI
'/Temp' is a relative URI
'~/Temp' is a relative URI
'file://C:/Temp' is a file URI
'file://Temp' is a UNC path
'http://something/Temp' is an absolute URI

like image 127
Richard Deeming Avatar answered Oct 08 '22 05:10

Richard Deeming