Windows Phone Developers

Thursday, October 30, 2008

Check if Path is Absolute or Relative Path using C# (.NET)

IsPathRooted method of Path class returns a value indicating whether the specified path string contains absolute or relative path information.

if (Path.IsPathRooted(@"c:\temp\") == true)

{

Console.WriteLine("Path is absolute");

}

else

{

Console.WriteLine("Path is relative");

}

How to find absolute path using C# (.NET), How to find relative path using C# (.NET), C# (.NET) Path Class, C# (.NET) IsPathRooted method Digg Technorati Delicious StumbleUpon Reddit BlinkList Furl Mixx Facebook Google Bookmark Yahoo
ma.gnolia squidoo newsvine live netscape tailrank mister-wong blogmarks slashdot spurl StumbleUpon

8 comments:

  1. but it returns true even if you give \temp\

    ReplyDelete
    Replies
    1. probably because you have \temp\ in your root folder.

      Delete
    2. Starting a path with "\" means "start at the root directory" effectively making the path a rooted path. Using ".\" and "..\" mean "current directory" and "current directory parent" making them relative paths.

      Try and see:
      Console.WriteLine(Path.IsPathRooted(@"\"));
      Console.WriteLine(Path.IsPathRooted(@".\"));
      Console.WriteLine(Path.IsPathRooted(@"..\"));

      Delete
  2. I think there it is better to use Regular Expressions:

    Regex meinReg = new Regex("^[a-zA-Z]{1}:\\.*");
    if (meinReg.Match(path) == Match.Empty)
    {
    return true;
    }
    return false;

    Best regards ;-)

    ReplyDelete
  3. Even if the post is older, if this hint can help somebody then :
    Use instead System.IO.Path.IsPathRooted(path)

    ReplyDelete
  4. Even if the post is older, if this hint can help somebody then :

    if (System.IO.Path.IsPathRooted(path)) {
    Console.WriteLine("Path is absolute");
    } else {
    Console.WriteLine("Path is relative");
    }

    ReplyDelete
  5. Unfortunately IsPathRooted does not mean that it is an absolute path(=completely deterministic path, which points to the same place from everywhere). It returns True for "c:file.txt", "\file.txt" as well.

    The matching regexp can be something similar:
    var ex = new Regex(@"^(([a-zA-Z]:\\)|(\\\\)).*");

    ReplyDelete
    Replies
    1. Thanks @eldor!
      Little fix:
      var ex = new Regex(@"^(([a-zA-Z]:\\)|(//)).*");

      cos of UNC path started with // like '//myserver/my_share/'

      Delete

kbAlertz.com :: Visual Studio 2005

kbAlertz.com :: Visual Studio 2008

kbAlertz.com :: Visual Basic 2005