I would like to know how to determine whether string is valid file path.
The file path may or may not exist.
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;
}
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;
}
DirectoryInfo directoryInfo = new DirectoryInfo(Path.GetFullPath(path));
try
{
if (!directoryInfo.Exists)
{
directoryInfo.Create();
}
}
catch (Exception ex)
{
if (Log.IsErrorEnabled)
{
Log.Error(ex.Message);
}
return false;
}`enter code here`
return true;
}
I found this at regexlib.com (http://regexlib.com/REDetails.aspx?regexp_id=345) by Dmitry Borysov.
"File Name Validator. Validates both UNC (\server\share\file) and regular MS path (c:\file)"
^(([a-zA-Z]:|\\)\\)?(((\.)|(\.\.)|([^\\/:\*\?"\|<>\. ](([^\\/:\*\?"\|<>\. ])|([^\\/:\*\?"\|<>]*[^\\/:\*\?"\|<>\. ]))?))\\)*[^\\/:\*\?"\|<>\. ](([^\\/:\*\?"\|<>\. ])|([^\\/:\*\?"\|<>]*[^\\/:\*\?"\|<>\. ]))?$
Run it with a Regex.IsMatch and you'll get a bool indicating if it's valid or not. I think regular expressions is the way to go since the file may not exist.
You can simply use Path.Combine() inside a try catch statement:
string path = @" your path ";
try
{
Path.Combine(path);
}
catch
{
MessageBox.Show("Invalid path");
}
Edit: Note that this function doesn't throw an exception if path contains wildcard characters ('*' and '?') since they can be used in search strings.
A 100% accurate checking of a path's string format is quite difficult, since it will depend on the filesystem on which it is used (and network protocols if its not on the same computer).
Even within windows or even NTFS its not simple since it still depends on the API .NET is using in the background to communicate with the kernel.
And since most filesystems today support unicode, one might also need to check for all the rules for correcly encoded unicode, normalization, etc etc.
What I'd do is to make some basic checks only, and then handle exceptions properly once the path is used. For possible rules see: