鉴于路径是这样的:如何从包含通配符的路径中提取目录?
C:\Temp\SomeDirectory\*.xml
我希望能够区分*.xml
从C:\Temp\SomeDirectory
不过,我不想目录的路径不具有尾随斜杠返回其父目录。
这意味着我想以下行为:
// Wildcard paths return directory
C:\Temp\SomeDirectory\*.csv -> C:\Temp\SomeDirectory
// Trailing slash paths return full path
C:\Temp\SomeDirectory\ -> C:\Temp\SomeDirectory
// Non-trailing slash paths to a directory return full path
C:\Temp\SomeDirectory -> C:\Temp\SomeDirectory
// Paths to a file return the directory
C:\Temp\SomeDirectory\SomeFileThatExists.csv -> C:\Temp\SomeDirectory
// Paths to a file without an extension (that exists) return the directory
C:\Temp\SomeDirectory\SomeFileThatExistsWithNoExt -> C:\Temp\SomeDirectory
// Paths to a non-existent path without a trailing slash are standard
// Either always clip the trailing part, or always leave it in
// (Can live with this one being C:\Temp\SomeDirectory)
C:\Temp\SomeDirectory\NonExistentObject -> C:\Temp\SomeDirectory\NonExistentObject
// Paths to a non-existent path with a trailing slash return the full path
C:\Temp\SomeDirectory\NonExistentObject\ -> C:\Temp\SomeDirectory\NonExistentObject
// Paths to a non-existent path with a file extension return the directory
C:\Temp\SomeDirectory\NonExistentFile.Ext -> C:\Temp\SomeDirectory
(我不是,如果返回值的尾随斜线与否,大惊小怪虽然我把下面的方法始终不返回尾部斜杠)
我当前的代码是这样的事情,并处理这些情况:
public string GetDirectory(string path)
{
try
{
var f = new FileInfo(path); // Throws if invalid path, e.g. wildcards
// Existent directory
if (Directory.Exists(path))
{
// Full path must be a directory, so return full path
// Ensure to add a trailing slash, as if it's missing it will return parent directory
return Path.GetDirectoryName(path + '/');
}
// Non-existent directory (or ambiguous path without an extension or trailing slash)
if (!System.IO.File.Exists(path) && String.IsNullOrEmpty(Path.GetExtension(path)))
{
// Path is to a non-existent file (without an extension) or to a non-existent directory.
// As the path does not exist we will standardise and treat it as a directory.
return Path.GetDirectoryName(path + '/');
}
// Path is to a file, return directory
return Path.GetDirectoryName(path);
}
catch (ArgumentException)
{
// For wildcards/invalid paths, return the directory
// This maps C:\Dir\*.csv to C:\Dir
// Also maps C:\Dir&*A*#[email protected]& to C:\
return Path.GetDirectoryName(path);
}
}
是否有更好的WA为了实现这种行为,或者我的终极目标是能够从可能包含通配符的路径中获取“目录”?
我的代码对于任何用户都有一个潜在的错误。如果路径是不存在的服务器根目录('\\ server \ someblah')中的文件的UNC样式路径(或没有结尾斜杠的目录),则将返回'null',而不是'\\服务器“,因为'\\ server'不是由'Path.GetDirectoryName'使用的规则所指定的目录。 –