122 c# validation file
System.IO命名空间中是否有一个检查文件名有效性的方法?
例如,C:\foo\bar将验证,:"~-*不会
或者有点棘手,X:\foo\bar会验证系统上是否有X:驱动器,否则不会.
我想我自己可以编写这样的方法,但我对内置的方法更感兴趣.
mmm*_*mmm 91
做就是了;
System.IO.FileInfo fi = null;
try {
fi = new System.IO.FileInfo(fileName);
}
catch (ArgumentException) { }
catch (System.IO.PathTooLongException) { }
catch (NotSupportedException) { }
if (ReferenceEquals(fi, null)) {
// file name is not valid
} else {
// file name is valid... May check for existence by calling fi.Exists.
}
Run Code Online (Sandbox Code Playgroud)
对于创建FileInfo实例,文件不需要存在.
Eug*_*atz 35
您可以从Path.GetInvalidPathChars和GetInvalidFileNameChars中获取无效字符列表,如本问题中所述.
正如jberger所指出的,还有一些其他字符未包含在此方法的响应中.有关Windows平台的更多详细信息,请查看MSDN 上的命名文件,路径和命名空间,
正如Micah 指出的那样,有Directory.GetLogicalDrives来获取有效驱动器的列表.
Lam*_*lex 11
您可以使用System.Uri类.Uri类不仅对Web URL有用,它还处理文件系统路径.使用Uri.TryCreate方法查找路径是否为root,然后使用IsLoopback属性确定Uri是否引用本地计算机.
这是一个简单的方法,用于确定字符串是否为有效,本地和根文件路径.
public bool IsPathValidRootedLocal(String pathString) {
Uri pathUri;
Boolean isValidUri = Uri.TryCreate(pathString, UriKind.Absolute, out pathUri);
return isValidUri && pathUri != null && pathUri.IsLoopback;
}
Run Code Online (Sandbox Code Playgroud)
我相信这会奏效.
您可以使用System.IO命名空间中存在的几种方法:
Directory.GetLogicalDrives() // Returns an array of strings like "c:\"
Path.GetInvalidFileNameChars() // Returns an array of characters that cannot be used in a file name
Path.GetInvalidPathChars() // Returns an array of characters that cannot be used in a path.
Run Code Online (Sandbox Code Playgroud)
如建议您可以这样做:
bool IsValidFilename(string testName) {
string regexString = "[" + Regex.Escape(Path.GetInvalidPathChars()) + "]";
Regex containsABadCharacter = new Regex(regexString);
if (containsABadCharacter.IsMatch(testName)) {
return false;
}
// Check for drive
string pathRoot = Path.GetPathRoot(testName);
if (Directory.GetLogicalDrives().Contains(pathRoot)) {
// etc
}
// other checks for UNC, drive-path format, etc
return true;
}
Run Code Online (Sandbox Code Playgroud)
即使文件名有效,您仍可能希望touch确保用户具有写入权限.
如果你不会在短时间内用数百个文件颠倒磁盘,我认为创建一个空文件是一种合理的方法.
如果你真的想要更轻松的东西,比如检查无效的字符,那么将你的文件名与Path.GetInvalidFileNameChars()进行比较.
小智 5
我想我会发布一个解决方案,该解决方案是我在寻找针对同一问题的可靠解决方案之后找到的答案的一部分。希望它可以帮助其他人。
using System;
using System.IO;
//..
public static bool ValidateFilePath(string path, bool RequireDirectory, bool IncludeFileName, bool RequireFileName = false)
{
if (string.IsNullOrEmpty(path)) { return false; }
string root = null;
string directory = null;
string filename = null;
try
{
// throw ArgumentException - The path parameter contains invalid characters, is empty, or contains only white spaces.
root = Path.GetPathRoot(path);
// throw ArgumentException - path contains one or more of the invalid characters defined in GetInvalidPathChars.
// -or- String.Empty was passed to path.
directory = Path.GetDirectoryName(path);
// path contains one or more of the invalid characters defined in GetInvalidPathChars
if (IncludeFileName) { filename = Path.GetFileName(path); }
}
catch (ArgumentException)
{
return false;
}
// null if path is null, or an empty string if path does not contain root directory information
if (String.IsNullOrEmpty(root)) { return false; }
// null if path denotes a root directory or is null. Returns String.Empty if path does not contain directory information
if (String.IsNullOrEmpty(directory)) { return false; }
if (RequireFileName)
{
// if the last character of path is a directory or volume separator character, this method returns String.Empty
if (String.IsNullOrEmpty(filename)) { return false; }
// check for illegal chars in filename
if (filename.IndexOfAny(Path.GetInvalidFileNameChars()) >= 0) { return false; }
}
return true;
}
Run Code Online (Sandbox Code Playgroud)