I am just wondering: I am looking for a way to validate if a given path is valid. (Note: I do not want to check if a file is existing! I only want to proof the validity
Try Uri.IsWellFormedUriString():
The string is not correctly escaped.
http://www.example.com/path???/file name
The string is an absolute Uri that represents an implicit file Uri.
c:\\directory\filename
The string is an absolute URI that is missing a slash before the path.
file://c:/directory/filename
The string contains unescaped backslashes even if they are treated as forward slashes.
http:\\host/path/file
The string represents a hierarchical absolute Uri and does not contain "://".
www.example.com/path/file
The parser for the Uri.Scheme indicates that the original string was not well-formed.
The example depends on the scheme of the URI.
Directory.Exists?
You can try this code:
try
{
Path.GetDirectoryName(myPath);
}
catch
{
// Path is not valid
}
I'm not sure it covers all the cases...
private bool IsValidPath(string path)
{
Regex driveCheck = new Regex(@"^[a-zA-Z]:\\$");
if (string.IsNullOrWhiteSpace(path) || path.Length < 3)
{
return false;
}
if (!driveCheck.IsMatch(path.Substring(0, 3)))
{
return false;
}
var x1 = (path.Substring(3, path.Length - 3));
string strTheseAreInvalidFileNameChars = new string(Path.GetInvalidPathChars());
strTheseAreInvalidFileNameChars += @":?*";
Regex containsABadCharacter = new Regex("[" + Regex.Escape(strTheseAreInvalidFileNameChars) + "]");
if (containsABadCharacter.IsMatch(path.Substring(3, path.Length - 3)))
{
return false;
}
var driveLetterWithColonAndSlash = Path.GetPathRoot(path);
if (!DriveInfo.GetDrives().Any(x => x.Name == driveLetterWithColonAndSlash))
{
return false;
}
return true;
}
You could try using Path.IsPathRooted() in combination with Path.GetInvalidFileNameChars() to make sure the path is half-way okay.
There are plenty of good solutions in here, but as none of then check if the path is rooted in an existing drive here's another one:
private bool IsValidPath(string path)
{
// Check if the path is rooted in a driver
if (path.Length < 3) return false;
Regex driveCheck = new Regex(@"^[a-zA-Z]:\\$");
if (!driveCheck.IsMatch(path.Substring(0, 3))) return false;
// Check if such driver exists
IEnumerable<string> allMachineDrivers = DriveInfo.GetDrives().Select(drive => drive.Name);
if (!allMachineDrivers.Contains(path.Substring(0, 3))) return false;
// Check if the rest of the path is valid
string InvalidFileNameChars = new string(Path.GetInvalidPathChars());
InvalidFileNameChars += @":/?*" + "\"";
Regex containsABadCharacter = new Regex("[" + Regex.Escape(InvalidFileNameChars) + "]");
if (containsABadCharacter.IsMatch(path.Substring(3, path.Length - 3)))
return false;
if (path[path.Length - 1] == '.') return false;
return true;
}
This solution does not take relative paths into account.