catch invalid file paths
I h开发者_如何学运维ave a function that reads a bunch of path-values (8 or 9 of them) from a text file. It uses these paths later in the application to read files. Whats the best way to check for validity of these file-paths. Can I do a single catch of some sorts?
System.IO.Directory.Exists(string path) System.IO.File.Exists(string path)
I would just use File.Exists in a loop, pretty simple and readable. Is there a trendier way? Probably.
You can use File.Exists
and/or Directory.Exists
is a path can be a directory.
static void Main(string[] args)
{
List<string> paths = new List<string>{"C:\\path1.txt", "c:\\path2.txt"};
bool allValid = paths.All(path=>File.Exists(path));
}
Maybe regex could be an option for you, at least in a windows environment. This avoids making a disk access, as File.Exists would. Source: http://www.csharp411.com/check-valid-file-path-in-c/
public bool IsValidPath(string path)
{
Regex r = new Regex( @"^(([a-zA-Z]\:)|(\\))(\\{1}|((\\{1})[^\\]([^/:*?<>""|]*))+)$" );
return r.IsMatch( path );
}
Consider using the System.IO.Path.GetFullPath
method. Like most of the members of the Path
class, it validates the path you pass in and throws an ArgumentException
if the path is invalid.
精彩评论