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

6 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

kbAlertz.com :: Visual Studio 2005

kbAlertz.com :: Visual Studio 2008

kbAlertz.com :: Visual Basic 2005