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");
}
but it returns true even if you give \temp\
ReplyDeleteprobably because you have \temp\ in your root folder.
DeleteStarting 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.
DeleteTry and see:
Console.WriteLine(Path.IsPathRooted(@"\"));
Console.WriteLine(Path.IsPathRooted(@".\"));
Console.WriteLine(Path.IsPathRooted(@"..\"));
I think there it is better to use Regular Expressions:
ReplyDeleteRegex meinReg = new Regex("^[a-zA-Z]{1}:\\.*");
if (meinReg.Match(path) == Match.Empty)
{
return true;
}
return false;
Best regards ;-)
Even if the post is older, if this hint can help somebody then :
ReplyDeleteUse instead System.IO.Path.IsPathRooted(path)
Even if the post is older, if this hint can help somebody then :
ReplyDeleteif (System.IO.Path.IsPathRooted(path)) {
Console.WriteLine("Path is absolute");
} else {
Console.WriteLine("Path is relative");
}
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.
ReplyDeleteThe matching regexp can be something similar:
var ex = new Regex(@"^(([a-zA-Z]:\\)|(\\\\)).*");
Thanks @eldor!
DeleteLittle fix:
var ex = new Regex(@"^(([a-zA-Z]:\\)|(//)).*");
cos of UNC path started with // like '//myserver/my_share/'