我想知道如何判断字符串是否是有效的文件路径。
文件路径可能存在,也可能不存在。
检查驱动器是否正确(例如,在一台计算机上驱动器 X:\ 存在,但在您的计算机上不存在):使用
Path.IsPathRooted
Environment.GetLogicalDrives()
中的驱动器查看如果您的路径包含有效驱动器之一。
要检查有效字符,有两种方法:
Path.GetInvalidFileNameChars()
Path.GetInvalidPathChars()
,它们不完全重叠。您还可以将
Path.GetDirectoryName(path)
和
Path.GetFileName(fileName)
与您的输入名称一起使用,这将抛出异常
,如果
在尝试创建该文件之前,您无法真正确定。也许路径有效,但安全设置不允许创建文件。唯一可以告诉您路径是否“真正”有效的实例是操作系统,那么为什么不尝试创建该文件并捕获表明该路径无效的“
IOException
。
你尝试过正则表达式吗?
^([a-zA-Z]\:)(\\[^\\/:*?<>"|]*(?<![ ]))*(\.[a-zA-Z]{2,6})$
尝试一下这个方法,它会尝试覆盖所有可能的异常情况。它适用于几乎所有 Windows 相关路径。
/// <summary>
/// Validate the Path. If path is relative append the path to the project directory by
/// default.
/// </summary>
/// <param name="path">Path to validate</param>
/// <param name="RelativePath">Relative path</param>
/// <param name="Extension">If want to check for File Path</param>
/// <returns></returns>
private static bool ValidateDllPath(ref string path,
string RelativePath = "",
string Extension = "")
{
// Check if it contains any Invalid Characters.
if (path.IndexOfAny(Path.GetInvalidPathChars()) == -1)
{
try
{
// If path is relative take %IGXLROOT% as the base directory
if (!Path.IsPathRooted(path))
{
if (string.IsNullOrEmpty(RelativePath))
{
// Exceptions handled by Path.GetFullPath
// ArgumentException path is a zero-length string, contains only white space,
// or contains one or more of the invalid characters defined in
// GetInvalidPathChars. -or- The system could not retrieve the absolute path.
//
// SecurityException The caller does not have the required permissions.
//
// ArgumentNullException path is null.
//
// NotSupportedException path contains a colon (":") that is not part of a
// volume identifier (for example, "c:\").
// PathTooLongException The specified path, file name, or both exceed the
// system-defined maximum length. For example, on Windows-based platforms,
// paths must be fewer than 248 characters, and file names must be fewer than
// 260 characters.
// RelativePath is not passed so we would take the project path
path = Path.GetFullPath(RelativePath);
}
else
{
// Make sure the path is relative to the RelativePath and not our project
// directory
path = Path.Combine(RelativePath, path);
}
}
// Exceptions from FileInfo Constructor:
// System.ArgumentNullException:
// fileName is null.
//
// System.Security.SecurityException:
// The caller does not have the required permission.
//
// System.ArgumentException:
// The file name is empty, contains only white spaces, or contains invalid
// characters.
//
// System.IO.PathTooLongException:
// The specified path, file name, or both exceed the system-defined maximum
// length. For example, on Windows-based platforms, paths must be less than
// 248 characters, and file names must be less than 260 characters.
//
// System.NotSupportedException:
// fileName contains a colon (:) in the middle of the string.
FileInfo fileInfo = new FileInfo(path);
// Exceptions using FileInfo.Length:
// System.IO.IOException:
// System.IO.FileSystemInfo.Refresh() cannot update the state of the file or
// directory.
//
// System.IO.FileNotFoundException:
// The file does not exist.-or- The Length property is called for a directory.
bool throwEx = fileInfo.Length == -1;
// Exceptions using FileInfo.IsReadOnly:
// System.UnauthorizedAccessException:
// Access to fileName is denied.
// The file described by the current System.IO.FileInfo object is read-only.
// -or- This operation is not supported on the current platform.
// -or- The caller does not have the required permission.
throwEx = fileInfo.IsReadOnly;
if (!string.IsNullOrEmpty(Extension))
{
// Validate the Extension of the file.
if (Path.GetExtension(path).Equals(Extension,
StringComparison.InvariantCultureIgnoreCase))
{
// Trim the Library Path
path = path.Trim();
return true;
}
else
{
return false;
}
}
else
{
return true;
}
}
catch (ArgumentNullException)
{
// System.ArgumentNullException:
// fileName is null.
}
catch (System.Security.SecurityException)
{
// System.Security.SecurityException:
// The caller does not have the required permission.
}
catch (ArgumentException)
{
// System.ArgumentException:
// The file name is empty, contains only white spaces, or contains invalid
// characters.
}
catch (UnauthorizedAccessException)
{
// System.UnauthorizedAccessException:
// Access to fileName is denied.
}
catch (PathTooLongException)
{
// System.IO.PathTooLongException:
// The specified path, file name, or both exceed the system-defined maximum
// length. For example, on Windows-based platforms, paths must be less than
// 248 characters, and file names must be less than 260 characters.
}
catch (NotSupportedException)
{
// System.NotSupportedException:
// fileName contains a colon (:) in the middle of the string.
}
catch (FileNotFoundException)
{
// System.FileNotFoundException
// The exception that is thrown when an attempt to access a file that does not
// exist on disk fails.
}
catch (IOException)
{
// System.IO.IOException:
// An I/O error occurred while opening the file.
}
catch (Exception)
{
// Unknown Exception. Might be due to wrong case or nulll checks.
}
}
else
{
// Path contains invalid characters
}
return false;
}
Regex driveCheck = new Regex(@"^[a-zA-Z]:\\$");
if (string.IsNullOrWhiteSpace(path) || path.Length < 3)
{
return false;
}
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 directoryInfo = new DirectoryInfo(Path.GetFullPath(path));
try
{
if (!directoryInfo.Exists)
{
directoryInfo.Create();
}
}
catch (Exception ex)
{
if (Log.IsErrorEnabled)
{
Log.Error(ex.Message);
}
return false;
}`enter code here`
return true;
}
http://regexlib.com/REDetails.aspx?regexp_id=345) 上找到了这个,作者:Dmitry Borysov。
您可以简单地在 try catch 语句中使用 Path.Combine() :
string path = @" your path ";
try
{
Path.Combine(path);
}
catch
{
MessageBox.Show("Invalid path");
}
编辑:
请注意,如果路径包含通配符(“*”和“?”),此函数不会引发异常,因为它们可以在搜索字符串中使用。
public static class PathHelper
{
public static bool IsValidPath(string path)
{
if (string.IsNullOrWhiteSpace(path))
return false;
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows) && path.Length > 260 && path.IndexOf("\\\\?") == -1)
return false;
if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux) && path.Length > 4096)
return false;
if (path.IndexOfAny(Path.GetInvalidPathChars()) >= 0)
return false;
var clearedPath = path;
if (Path.IsPathRooted(path))
{
var disk = Path.GetPathRoot(path);
if (path.IndexOf(disk) > 0)
return false;
clearedPath = path.Replace(disk, string.Empty);
}
return clearedPath.Split(Path.DirectorySeparatorChar).All(segment => segment.IndexOfAny(Path.GetInvalidFileNameChars()) == -1);
}
}