Cor*_*ott 101 .net c# winapi path
我只是想知道:我正在寻找一种方法来验证给定路径是否有效. (注意:我不想检查文件是否存在!我只想证明路径的有效性 - 所以如果文件可能存在于该位置).
问题是,我在.Net API中找不到任何东西.由于Windows支持的许多格式和位置,我宁愿使用MS-native.
由于该功能应该能够检查:
- 相对路径(./)
- 绝对路径(c:\ tmp)
- UNC-Pathes(\ some-pc\c $)
- NTFS限制,如完整路径1024个字符 - 如果我没有错误超过路径将使许多内部Windows功能无法访问文件.用Explorer重命名它仍然有效
- 卷GUID路径:"\?\ Volume {GUID}\somefile.foo
有没有人有这样的功能?
aba*_*hev 56
试试Uri.IsWellFormedUriString():
字符串未正确转义.
http://www.example.com/path???/file name
Run Code Online (Sandbox Code Playgroud)字符串是绝对的Uri,表示隐式文件Uri.
c:\\directory\filename
Run Code Online (Sandbox Code Playgroud)字符串是绝对URI,在路径之前缺少斜杠.
file://c:/directory/filename
Run Code Online (Sandbox Code Playgroud)该字符串包含未转义的反斜杠,即使它们被视为正斜杠也是如此.
http:\\host/path/file
Run Code Online (Sandbox Code Playgroud)该字符串表示分层绝对Uri,不包含"://".
www.example.com/path/file
Run Code Online (Sandbox Code Playgroud)Uri.Scheme的解析器表明原始字符串格式不正确.
The example depends on the scheme of the URI.
Run Code Online (Sandbox Code Playgroud)private bool IsValidPath(string path)
{
Regex driveCheck = new Regex(@"^[a-zA-Z]:\\$");
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 dir = new DirectoryInfo(Path.GetFullPath(path));
if (!dir.Exists)
dir.Create();
return true;
}
Run Code Online (Sandbox Code Playgroud)
你可以试试这个代码:
try
{
Path.GetDirectoryName(myPath);
}
catch
{
// Path is not valid
}
Run Code Online (Sandbox Code Playgroud)
我不确定它涵盖了所有情况......
小智 6
我对下面的代码没有任何问题.(相对路径必须以'/'或'\'开头).
private bool IsValidPath(string path, bool allowRelativePaths = false)
{
bool isValid = true;
try
{
string fullPath = Path.GetFullPath(path);
if (allowRelativePaths)
{
isValid = Path.IsPathRooted(path);
}
else
{
string root = Path.GetPathRoot(path);
isValid = string.IsNullOrEmpty(root.Trim(new char[] { '\\', '/' })) == false;
}
}
catch(Exception ex)
{
isValid = false;
}
return isValid;
}
Run Code Online (Sandbox Code Playgroud)
例如,这些将返回false:
IsValidPath("C:/abc*d");
IsValidPath("C:/abc?d");
IsValidPath("C:/abc\"d");
IsValidPath("C:/abc<d");
IsValidPath("C:/abc>d");
IsValidPath("C:/abc|d");
IsValidPath("C:/abc:d");
IsValidPath("");
IsValidPath("./abc");
IsValidPath("./abc", true);
IsValidPath("/abc");
IsValidPath("abc");
IsValidPath("abc", true);
Run Code Online (Sandbox Code Playgroud)
这些将返回真实:
IsValidPath(@"C:\\abc");
IsValidPath(@"F:\FILES\");
IsValidPath(@"C:\\abc.docx\\defg.docx");
IsValidPath(@"C:/abc/defg");
IsValidPath(@"C:\\\//\/\\/\\\/abc/\/\/\/\///\\\//\defg");
IsValidPath(@"C:/abc/def~`!@#$%^&()_-+={[}];',.g");
IsValidPath(@"C:\\\\\abc////////defg");
IsValidPath(@"/abc", true);
IsValidPath(@"\abc", true);
Run Code Online (Sandbox Code Playgroud)