结合其他答案的建议后,我意识到我想到了与Ronnie Overby的答案相同的东西。以下是一些测试,指出了一些需要考虑的事项:
- 文件夹可以具有“扩展名”:
C:\Temp\folder_with.dot
- 文件不能以目录分隔符(斜杠)结尾
- 从技术上讲,有两个特定于平台的目录分隔符-即可以是斜线(和),也可以不是
Path.DirectorySeparatorChar
Path.AltDirectorySeparatorChar
测试(Linqpad)
var paths = new[] {
// exists
@"C:\Temp\dir_test\folder_is_a_dir",
@"C:\Temp\dir_test\is_a_dir_trailing_slash\",
@"C:\Temp\dir_test\existing_folder_with.ext",
@"C:\Temp\dir_test\file_thats_not_a_dir",
@"C:\Temp\dir_test\notadir.txt",
// doesn't exist
@"C:\Temp\dir_test\dne_folder_is_a_dir",
@"C:\Temp\dir_test\dne_folder_trailing_slash\",
@"C:\Temp\dir_test\non_existing_folder_with.ext",
@"C:\Temp\dir_test\dne_file_thats_not_a_dir",
@"C:\Temp\dir_test\dne_notadir.txt",
};
foreach(var path in paths) {
IsFolder(path/*, false*/).Dump(path);
}
结果
C:\Temp\dir_test\folder_is_a_dir
True
C:\Temp\dir_test\is_a_dir_trailing_slash\
True
C:\Temp\dir_test\existing_folder_with.ext
True
C:\Temp\dir_test\file_thats_not_a_dir
False
C:\Temp\dir_test\notadir.txt
False
C:\Temp\dir_test\dne_folder_is_a_dir
True
C:\Temp\dir_test\dne_folder_trailing_slash\
True
C:\Temp\dir_test\non_existing_folder_with.ext
False (this is the weird one)
C:\Temp\dir_test\dne_file_thats_not_a_dir
True
C:\Temp\dir_test\dne_notadir.txt
False
方法
/// <summary>
/// Whether the <paramref name="path"/> is a folder (existing or not);
/// optionally assume that if it doesn't "look like" a file then it's a directory.
/// </summary>
/// <param name="path">Path to check</param>
/// <param name="assumeDneLookAlike">If the <paramref name="path"/> doesn't exist, does it at least look like a directory name? As in, it doesn't look like a file.</param>
/// <returns><c>True</c> if a folder/directory, <c>false</c> if not.</returns>
public static bool IsFolder(string path, bool assumeDneLookAlike = true)
{
// /programming/1395205/better-way-to-check-if-path-is-a-file-or-a-directory
// turns out to be about the same as https://stackoverflow.com/a/19596821/1037948
// check in order of verisimilitude
// exists or ends with a directory separator -- files cannot end with directory separator, right?
if (Directory.Exists(path)
// use system values rather than assume slashes
|| path.EndsWith("" + Path.DirectorySeparatorChar)
|| path.EndsWith("" + Path.AltDirectorySeparatorChar))
return true;
// if we know for sure that it's an actual file...
if (File.Exists(path))
return false;
// if it has an extension it should be a file, so vice versa
// although technically directories can have extensions...
if (!Path.HasExtension(path) && assumeDneLookAlike)
return true;
// only works for existing files, kinda redundant with `.Exists` above
//if( File.GetAttributes(path).HasFlag(FileAttributes.Directory) ) ...;
// no idea -- could return an 'indeterminate' value (nullable bool)
// or assume that if we don't know then it's not a folder
return false;
}