您可以使用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
什么应该是有效的路径? – Habib
我编辑了我的问题.. – CMA
你想说如果路径有“\”或“/”将是无效的? – khan