I would like to know how to determine whether string is valid file path.
我想知道如何确定字符串是否是有效的文件路径。
The file path may or may not exist.
文件路径可能存在也可能不存在。
10 个解决方案
#1
20
A 100% accurate checking of a path's string format is quite difficult, since it will depend on the filesystem on which it is used (and network protocols if its not on the same computer).
100%准确地检查路径的字符串格式是非常困难的,因为它将取决于使用它的文件系统(如果它不在同一台计算机上,则取决于网络协议)。
Even within windows or even NTFS its not simple since it still depends on the API .NET is using in the background to communicate with the kernel.
即使在Windows甚至NTFS中,它也不简单,因为它依赖于.NET .NET在后台使用以与内核通信。
And since most filesystems today support unicode, one might also need to check for all the rules for correcly encoded unicode, normalization, etc etc.
由于目前大多数文件系统都支持unicode,因此可能还需要检查所有规则以进行正确编码的unicode,规范化等。
What I'd do is to make some basic checks only, and then handle exceptions properly once the path is used. For possible rules see:
我要做的只是进行一些基本检查,然后在使用路径后正确处理异常。有关规则,请参阅:
- Wikipedia - Filename for an overview of the rules used by different file systems
- Wikipedia - 文件名,用于概述不同文件系统使用的规则
- Naming Files, Paths, and Namespaces for windows specific rules
- 为Windows特定规则命名文件,路径和命名空间
#2
49
You can use the FileInfo constructor. It will throw a ArgumentException if "The file name is empty, contains only white spaces, or contains invalid characters." It can also throw SecurityException or UnauthorizedAccessException, which I think you can ignore if you're only concerned about format.
您可以使用FileInfo构造函数。如果“文件名为空,仅包含空格或包含无效字符”,它将抛出ArgumentException。它也可以抛出SecurityException或UnauthorizedAccessException,如果你只关心格式,我认为你可以忽略它。
Another option is to check against Path.GetInvalidPathChars directly. E.g.:
另一种选择是直接检查Path.GetInvalidPathChars。例如。:
boolean possiblePath = pathString.IndexOfAny(Path.GetInvalidPathChars()) == -1;
#3
8
Here are some things you might use:
以下是您可能会使用的一些内容:
- to check if the drive is correct (for example on one computer the drive X:\ exists, but not on yours): use
Path.IsPathRooted
to see if it's not a relative path and then use the drives fromEnvironment.GetLogicalDrives()
to see if your path contains one of the valid drives. - 检查驱动器是否正确(例如,在一台计算机上,驱动器X:\存在,但不存在于您的驱动器上):使用Path.IsPathRooted查看它是否不是相对路径,然后使用来自Environment.GetLogicalDrives()的驱动器看看你的路径是否包含一个有效的驱动器。
- To check for valid characters, you have two methods:
Path.GetInvalidFileNameChars()
andPath.GetInvalidPathChars()
which don't overlap completely. You can also usePath.GetDirectoryName(path)
andPath.GetFileName(fileName)
with your input name, which will throw an exception if - 要检查有效字符,您有两种方法:Path.GetInvalidFileNameChars()和Path.GetInvalidPathChars(),它们不完全重叠。您还可以将Path.GetDirectoryName(path)和Path.GetFileName(fileName)与您的输入名称一起使用,如果输入名称将引发异常,
The path parameter contains invalid characters, is empty, or contains only white spaces.
path参数包含无效字符,为空或仅包含空格。
#4
3
You cant really be sure until you try to create that file. Maybe the path is valid but security settings wont allow creation of the file. The only instance that could tell you if the path is REALLY valid would be the OS, so why dont you try to create that file an catch the IOException which indicates something went really wrong? Imho this is the easier approach: assume the input is valid and do something if it isnt, instead of doing much unnecessary work.
在尝试创建该文件之前,您无法确定。也许路径是有效的,但安全设置不允许创建文件。可以告诉你路径是否真的有效的唯一实例是操作系统,那么为什么不尝试创建该文件捕获IOException,这表明出现了什么问题呢? Imho这是一种更简单的方法:假设输入是有效的,如果不是,则做一些事情,而不是做很多不必要的工作。
#5
2
Have you tried regular expressions?
你试过正则表达式吗?
^([a-zA-Z]\:)(\\[^\\/:*?<>"|]*(?<![ ]))*(\.[a-zA-Z]{2,6})$
should work
应该管用
#6
1
Try out this method which would try to cover for all the possible Exceptions scenarios. It would work for almost all the Windows related Paths.
尝试这种方法,试图涵盖所有可能的异常情况。它适用于几乎所有与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 less than 248 characters, and file names must be less 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;
}
#7
1
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;
}
#8
0
I found this at regexlib.com (http://regexlib.com/REDetails.aspx?regexp_id=345) by Dmitry Borysov.
我在dmitry Borysov的regexlib.com(http://regexlib.com/REDetails.aspx?regexp_id=345)上找到了这个。
"File Name Validator. Validates both UNC (\server\share\file) and regular MS path (c:\file)"
“文件名验证器。验证UNC(\ server \ share \ file)和常规MS路径(c:\ file)”
^(([a-zA-Z]:|\\)\\)?(((\.)|(\.\.)|([^\\/:\*\?"\|<>\. ](([^\\/:\*\?"\|<>\. ])|([^\\/:\*\?"\|<>]*[^\\/:\*\?"\|<>\. ]))?))\\)*[^\\/:\*\?"\|<>\. ](([^\\/:\*\?"\|<>\. ])|([^\\/:\*\?"\|<>]*[^\\/:\*\?"\|<>\. ]))?$
Run it with a Regex.IsMatch and you'll get a bool indicating if it's valid or not. I think regular expressions is the way to go since the file may not exist.
使用Regex.IsMatch运行它,你会得到一个bool,表明它是否有效。我认为正则表达式是可行的,因为该文件可能不存在。
#9
0
You can simply use Path.Combine() inside a try catch statement:
您可以在try catch语句中使用Path.Combine():
string path = @" your path ";
try
{
Path.Combine(path);
}
catch
{
MessageBox.Show("Invalid path");
}
Edit: Note that this function doesn't throw an exception if path contains wildcard characters ('*' and '?') since they can be used in search strings.
编辑:请注意,如果路径包含通配符('*'和'?'),则此函数不会引发异常,因为它们可用于搜索字符串。
#10
0
The static class System.IO.Path can do what you're asking for.
静态类System.IO.Path可以做你想要的。
#1
20
A 100% accurate checking of a path's string format is quite difficult, since it will depend on the filesystem on which it is used (and network protocols if its not on the same computer).
100%准确地检查路径的字符串格式是非常困难的,因为它将取决于使用它的文件系统(如果它不在同一台计算机上,则取决于网络协议)。
Even within windows or even NTFS its not simple since it still depends on the API .NET is using in the background to communicate with the kernel.
即使在Windows甚至NTFS中,它也不简单,因为它依赖于.NET .NET在后台使用以与内核通信。
And since most filesystems today support unicode, one might also need to check for all the rules for correcly encoded unicode, normalization, etc etc.
由于目前大多数文件系统都支持unicode,因此可能还需要检查所有规则以进行正确编码的unicode,规范化等。
What I'd do is to make some basic checks only, and then handle exceptions properly once the path is used. For possible rules see:
我要做的只是进行一些基本检查,然后在使用路径后正确处理异常。有关规则,请参阅:
- Wikipedia - Filename for an overview of the rules used by different file systems
- Wikipedia - 文件名,用于概述不同文件系统使用的规则
- Naming Files, Paths, and Namespaces for windows specific rules
- 为Windows特定规则命名文件,路径和命名空间
#2
49
You can use the FileInfo constructor. It will throw a ArgumentException if "The file name is empty, contains only white spaces, or contains invalid characters." It can also throw SecurityException or UnauthorizedAccessException, which I think you can ignore if you're only concerned about format.
您可以使用FileInfo构造函数。如果“文件名为空,仅包含空格或包含无效字符”,它将抛出ArgumentException。它也可以抛出SecurityException或UnauthorizedAccessException,如果你只关心格式,我认为你可以忽略它。
Another option is to check against Path.GetInvalidPathChars directly. E.g.:
另一种选择是直接检查Path.GetInvalidPathChars。例如。:
boolean possiblePath = pathString.IndexOfAny(Path.GetInvalidPathChars()) == -1;
#3
8
Here are some things you might use:
以下是您可能会使用的一些内容:
- to check if the drive is correct (for example on one computer the drive X:\ exists, but not on yours): use
Path.IsPathRooted
to see if it's not a relative path and then use the drives fromEnvironment.GetLogicalDrives()
to see if your path contains one of the valid drives. - 检查驱动器是否正确(例如,在一台计算机上,驱动器X:\存在,但不存在于您的驱动器上):使用Path.IsPathRooted查看它是否不是相对路径,然后使用来自Environment.GetLogicalDrives()的驱动器看看你的路径是否包含一个有效的驱动器。
- To check for valid characters, you have two methods:
Path.GetInvalidFileNameChars()
andPath.GetInvalidPathChars()
which don't overlap completely. You can also usePath.GetDirectoryName(path)
andPath.GetFileName(fileName)
with your input name, which will throw an exception if - 要检查有效字符,您有两种方法:Path.GetInvalidFileNameChars()和Path.GetInvalidPathChars(),它们不完全重叠。您还可以将Path.GetDirectoryName(path)和Path.GetFileName(fileName)与您的输入名称一起使用,如果输入名称将引发异常,
The path parameter contains invalid characters, is empty, or contains only white spaces.
path参数包含无效字符,为空或仅包含空格。
#4
3
You cant really be sure until you try to create that file. Maybe the path is valid but security settings wont allow creation of the file. The only instance that could tell you if the path is REALLY valid would be the OS, so why dont you try to create that file an catch the IOException which indicates something went really wrong? Imho this is the easier approach: assume the input is valid and do something if it isnt, instead of doing much unnecessary work.
在尝试创建该文件之前,您无法确定。也许路径是有效的,但安全设置不允许创建文件。可以告诉你路径是否真的有效的唯一实例是操作系统,那么为什么不尝试创建该文件捕获IOException,这表明出现了什么问题呢? Imho这是一种更简单的方法:假设输入是有效的,如果不是,则做一些事情,而不是做很多不必要的工作。
#5
2
Have you tried regular expressions?
你试过正则表达式吗?
^([a-zA-Z]\:)(\\[^\\/:*?<>"|]*(?<![ ]))*(\.[a-zA-Z]{2,6})$
should work
应该管用
#6
1
Try out this method which would try to cover for all the possible Exceptions scenarios. It would work for almost all the Windows related Paths.
尝试这种方法,试图涵盖所有可能的异常情况。它适用于几乎所有与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 less than 248 characters, and file names must be less 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;
}
#7
1
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;
}
#8
0
I found this at regexlib.com (http://regexlib.com/REDetails.aspx?regexp_id=345) by Dmitry Borysov.
我在dmitry Borysov的regexlib.com(http://regexlib.com/REDetails.aspx?regexp_id=345)上找到了这个。
"File Name Validator. Validates both UNC (\server\share\file) and regular MS path (c:\file)"
“文件名验证器。验证UNC(\ server \ share \ file)和常规MS路径(c:\ file)”
^(([a-zA-Z]:|\\)\\)?(((\.)|(\.\.)|([^\\/:\*\?"\|<>\. ](([^\\/:\*\?"\|<>\. ])|([^\\/:\*\?"\|<>]*[^\\/:\*\?"\|<>\. ]))?))\\)*[^\\/:\*\?"\|<>\. ](([^\\/:\*\?"\|<>\. ])|([^\\/:\*\?"\|<>]*[^\\/:\*\?"\|<>\. ]))?$
Run it with a Regex.IsMatch and you'll get a bool indicating if it's valid or not. I think regular expressions is the way to go since the file may not exist.
使用Regex.IsMatch运行它,你会得到一个bool,表明它是否有效。我认为正则表达式是可行的,因为该文件可能不存在。
#9
0
You can simply use Path.Combine() inside a try catch statement:
您可以在try catch语句中使用Path.Combine():
string path = @" your path ";
try
{
Path.Combine(path);
}
catch
{
MessageBox.Show("Invalid path");
}
Edit: Note that this function doesn't throw an exception if path contains wildcard characters ('*' and '?') since they can be used in search strings.
编辑:请注意,如果路径包含通配符('*'和'?'),则此函数不会引发异常,因为它们可用于搜索字符串。
#10
0
The static class System.IO.Path can do what you're asking for.
静态类System.IO.Path可以做你想要的。