通过C#确定字符串是否为有效的文件路径
我想知道如何确定字符串是否是有效的文件路径 文件路径可能存在,也可能不存在。您可以使用构造函数。如果“文件名为空、仅包含空格或包含无效字符”,它将抛出ArgumentException。它还可以抛出SecurityException或UnauthorizedAccessException,如果您只关心格式,我认为您可以忽略这些 另一种选择是直接对照检查。例如:通过C#确定字符串是否为有效的文件路径,c#,.net,validation,path,filesystems,C#,.net,Validation,Path,Filesystems,我想知道如何确定字符串是否是有效的文件路径 文件路径可能存在,也可能不存在。您可以使用构造函数。如果“文件名为空、仅包含空格或包含无效字符”,它将抛出ArgumentException。它还可以抛出SecurityException或UnauthorizedAccessException,如果您只关心格式,我认为您可以忽略这些 另一种选择是直接对照检查。例如: boolean possiblePath = pathString.IndexOfAny(Path.GetInvalidPathChar
boolean possiblePath = pathString.IndexOfAny(Path.GetInvalidPathChars()) == -1;
你试过正则表达式吗
^([a-zA-Z]\:)(\\[^\\/:*?<>"|]*(?<![ ]))*(\.[a-zA-Z]{2,6})$
^([a-zA-Z]\:)(\\[^\\/:*?“\;]*(?)?
如果可行100%准确地检查路径的字符串格式是相当困难的,因为它将取决于使用它的文件系统(如果它不在同一台计算机上,则取决于网络协议)
即使在windows甚至NTFS中,这也不简单,因为它仍然依赖于API。NET在后台与内核通信
由于现在大多数文件系统都支持unicode,因此可能还需要检查正确编码的unicode、规范化等的所有规则
我要做的是只进行一些基本检查,然后在使用路径后正确处理异常。有关可能的规则,请参阅:
- 有关不同文件系统使用的规则的概述
- 对于windows特定规则
我在regexlib.com()上找到了这篇文章,作者是Dmitry Borysov
“文件名验证程序。验证UNC(\server\share\File)和常规MS路径(c:\File)”
(2)以下以下::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::“\\.]”)吗$
使用Regex.IsMatch运行它,您将得到一个bool,指示它是否有效。我认为正则表达式是一种方法,因为该文件可能不存在。静态类System.IO.Path可以满足您的要求。以下是一些您可以使用的方法:
- 要检查驱动器是否正确(例如,在一台计算机上,驱动器X:\存在,但不在您的计算机上):使用
查看它是否不是相对路径,然后使用Path.IsPathRooted
中的驱动器查看您的路径是否包含一个有效的驱动器Environment.GetLogicalDrives()
- 要检查有效字符,您有两种方法:
和Path.GetInvalidFileNameChars()
,它们不会完全重叠。您还可以将Path.GetInvalidPathChars()
和Path.GetDirectoryName(Path)
与输入名称一起使用,如果Path.GetFileName(fileName)
在尝试创建该文件之前,您无法真正确定。可能路径有效,但安全设置不允许创建该文件。唯一可以告诉您该路径是否真的有效的实例是操作系统,因此,为什么不尝试创建该文件以捕获指示其无效的
IOException
根据我的观点,这是一种方法:假设输入有效,使用它,并在无效时捕获一个IOException
。您只需在try-catch语句中使用Path.Combine()
string path = @" your path ";
try
{
Path.Combine(path);
}
catch
{
MessageBox.Show("Invalid path");
}
编辑:
请注意,如果路径包含通配符(“*”和“?”),此函数不会引发异常,因为它们可以在搜索字符串中使用。尝试此方法,该方法将尝试涵盖所有可能的异常情况。它将适用于几乎所有与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;
}
//
///验证路径。如果路径是相对路径,请通过以下方式将路径附加到项目目录
///默认。
///
///验证路径
///相对路径
///如果要检查文件路径
///
私有静态bool ValidateDllPath(参考字符串路径,
字符串RelativePath=“”,
字符串扩展名=“”)
{
//检查它是否包含任何无效字符。
if(path.IndexOfAny(path.GetInvalidPathChars())==-1)
{
尝试
{
//如果路径是相对的,则将%IGXLROOT%作为基本目录
如果(!Path.IsPathRooted(Path))
{
if(string.IsNullOrEmpty(RelativePath))
{
//由Path.GetFullPath处理的异常
//ArgumentException路径为零长度字符串,仅包含空格,
//或包含中定义的一个或多个无效字符
//GetInvalidPathChars.-或-系统无法检索绝对路径。
//
//SecurityException调用方没有所需的权限。
//
//ArgumentNullException路径为空。
//
//NotSupportedException路径包含不属于
//卷标识符(例如,“c:\”)。
//PathTooLongException指定的路径、文件名或两者都超过
//系统定义的最大长度。例如,在基于Windows的平台上,
//路径必须少于248个字符,文件名必须少于
//260个字符。
//RelativePath未通过,因此我们将采用项目路径
path=path.GetFullPath(RelativePath);
}
其他的
{
//确保路径相对于RelativePath,而不是我们的项目
//目录
路径=路径。组合(相对路径,路径);
}
}
//FileInfo构造函数的例外情况:
//System.ArgumentNullException:
//文件名为空。
//
//System.Security.SecurityException:
//调用方没有所需的权限。
//
//System.ArgumentException:
//文件名为空、仅包含空格或包含无效的
//人物。
//
//System.IO.PathTooLongException
/// <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;
}