您可以使用Path.GetFullPath,如果路径无效,它将引发异常。你可以有这样的方法:
public static bool IsValidPath(string path)
{
try
{
path = path.Replace(@"\\", ":"); // to cancel out c:\\\\test.text
string temp = Path.GetPathRoot(path); //For cases like: \text.txt
if (temp.StartsWith(@"\"))
return false;
string pt = Path.GetFullPath(path);
}
catch //(Exception NotSupportedException) // catch specific exception here or not if you want
{
return false;
}
return true;
}
要测试的示例代码:
List<string> list = new List<string>()
{
@":\text.txt",
@":text.txt",
@"\:text.txt",
@"\text.txt",
@"C:\\\text.txt",
@"C:\text.txt",
};
foreach(string str in list)
{
Console.WriteLine("Path: {0} is Valid = {1}" ,str,IsValidPath(str));
}
输出:
Path: :\text.txt is Valid = False
Path: :text.txt is Valid = False
Path: \:text.txt is Valid = False
Path: \text.txt is Valid = False
Path: C:\\\text.txt is Valid = False
Path: C:\text.txt is Valid = True