字符串路径验证 [英] String path validation
问题描述
我在这里有一个字符串(来自用户的输入)作为文件路径.我检查了字符串,以使其符合条件:
I have here a string(an input from the user) for a file path. I checked the string so that it will qualify the criteria:
- 检查文件路径中的无效字符
- 将不接受绝对路径 (\ Sample \ text.txt)
- check for invalid characters for a file path
- will not accept absolute path (\Sample\text.txt)
无效字符为:
< >:"/\ |?*
< > : " / \ | ? *
我尝试在catch子句中捕获这些无效字符.除"\"外,它均有效.它将接受"C:\\ Sample \ text.txt",这是无效的文件路径.
I have tried catching these invalid characters in catch clause. It work except for '\'. It will accept 'C:\\Sample\text.txt' which is an invalid file path.
以下示例应为无效路径:
- :\ text.txt
- :text.txt
- \:text.txt
- \ text.txt
- C:\\\ text.txt
ff.是有效路径的示例:
- C:\ text.txt
我曾经遇到过类似的问题,但似乎没有一个能解决我的问题.
I have been through similar questions posted here but none of them seemed to solve my issue.
进行这种检查的最佳方法是什么?
What would be the best way to do such check?
推荐答案
You may use Path.GetFullPath, it will throw an exception if the path is invalid. You can have method like:
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
这篇关于字符串路径验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!