我正在处理目录和文件的 TreeView
。用户可以选择文件或目录,然后对其进行操作。这需要我有一种方法可以根据用户的选择执行不同的操作。
目前我正在做这样的事情来确定路径是文件还是目录:
bool bIsFile = false;
bool bIsDirectory = false;
try
{
string[] subfolders = Directory.GetDirectories(strFilePath);
bIsDirectory = true;
bIsFile = false;
}
catch(System.IO.IOException)
{
bIsFolder = false;
bIsFile = true;
}
我不禁觉得有更好的方法来做到这一点!我希望找到一种标准的 .NET 方法来处理这个问题,但我一直没能做到。是否存在这样的方法,如果没有,确定路径是文件还是目录的最直接方法是什么?
从 How to tell if path is file or directory:
// get the file attributes for file or directory
FileAttributes attr = File.GetAttributes(@"c:\Temp");
//detect whether its a directory or file
if ((attr & FileAttributes.Directory) == FileAttributes.Directory)
MessageBox.Show("Its a directory");
else
MessageBox.Show("Its a file");
.NET 4.0+ 的更新
根据下面的评论,如果您使用 .NET 4.0 或更高版本(并且最大性能并不重要),您可以以更简洁的方式编写代码:
// get the file attributes for file or directory
FileAttributes attr = File.GetAttributes(@"c:\Temp");
if (attr.HasFlag(FileAttributes.Directory))
MessageBox.Show("Its a directory");
else
MessageBox.Show("Its a file");
用这些怎么样?
File.Exists();
Directory.Exists();
File.GetAttributes()
不同,这还具有不会在无效路径上引发异常的优点。
public static bool? IsDirectory(string path){
if (Directory.Exists(path))
return true; // is a directory
else if (File.Exists(path))
return false; // is a file
else
return null; // is a nothing
}
仅使用这一行,您就可以获得路径是目录还是文件:
File.GetAttributes(data.Path).HasFlag(FileAttributes.Directory)
这是我的:
bool IsPathDirectory(string path)
{
if (path == null) throw new ArgumentNullException("path");
path = path.Trim();
if (Directory.Exists(path))
return true;
if (File.Exists(path))
return false;
// neither file nor directory exists. guess intention
// if has trailing slash then it's a directory
if (new[] {"\\", "/"}.Any(x => path.EndsWith(x)))
return true; // ends with slash
// if has extension then its a file; directory otherwise
return string.IsNullOrWhiteSpace(Path.GetExtension(path));
}
它与其他人的答案相似,但不完全相同。
Path.DirectorySeparatorChar
和 Path.AltDirectorySeparatorChar
作为 Directory.Exists() 的替代方法,您可以使用 File.GetAttributes() 方法来获取文件或目录的属性,因此您可以创建如下帮助方法:
private static bool IsDirectory(string path)
{
System.IO.FileAttributes fa = System.IO.File.GetAttributes(path);
return (fa & FileAttributes.Directory) != 0;
}
在填充包含项目的其他元数据的控件时,您还可以考虑将对象添加到 TreeView 控件的标记属性。例如,您可以为文件添加一个 FileInfo 对象,为目录添加一个 DirectoryInfo 对象,然后在标签属性中测试项目类型,以节省在单击项目时进行额外的系统调用以获取该数据。
isDirectory = (fa & FileAttributes.Directory) != 0);
在结合其他答案的建议后,我意识到我想出了与 Ronnie Overby's answer 大致相同的东西。这里有一些测试指出一些需要考虑的事情:
文件夹可以有“扩展名”: 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)
{
// https://stackoverflow.com/questions/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;
}
Path.DirectorySeparatorChar.ToString()
而不是字符串与 ""
连接?
ToString
那样执行 new String(Path.DirectorySeparatorChar, 1)
。
鉴于 Exists 和 Attributes 属性的行为,这是我能想到的最好的方法:
using System.IO;
public static class FileSystemInfoExtensions
{
/// <summary>
/// Checks whether a FileInfo or DirectoryInfo object is a directory, or intended to be a directory.
/// </summary>
/// <param name="fileSystemInfo"></param>
/// <returns></returns>
public static bool IsDirectory(this FileSystemInfo fileSystemInfo)
{
if (fileSystemInfo == null)
{
return false;
}
if ((int)fileSystemInfo.Attributes != -1)
{
// if attributes are initialized check the directory flag
return fileSystemInfo.Attributes.HasFlag(FileAttributes.Directory);
}
// If we get here the file probably doesn't exist yet. The best we can do is
// try to judge intent. Because directories can have extensions and files
// can lack them, we can't rely on filename.
//
// We can reasonably assume that if the path doesn't exist yet and
// FileSystemInfo is a DirectoryInfo, a directory is intended. FileInfo can
// make a directory, but it would be a bizarre code path.
return fileSystemInfo is DirectoryInfo;
}
}
以下是它的测试方式:
[TestMethod]
public void IsDirectoryTest()
{
// non-existing file, FileAttributes not conclusive, rely on type of FileSystemInfo
const string nonExistentFile = @"C:\TotallyFakeFile.exe";
var nonExistentFileDirectoryInfo = new DirectoryInfo(nonExistentFile);
Assert.IsTrue(nonExistentFileDirectoryInfo.IsDirectory());
var nonExistentFileFileInfo = new FileInfo(nonExistentFile);
Assert.IsFalse(nonExistentFileFileInfo.IsDirectory());
// non-existing directory, FileAttributes not conclusive, rely on type of FileSystemInfo
const string nonExistentDirectory = @"C:\FakeDirectory";
var nonExistentDirectoryInfo = new DirectoryInfo(nonExistentDirectory);
Assert.IsTrue(nonExistentDirectoryInfo.IsDirectory());
var nonExistentFileInfo = new FileInfo(nonExistentDirectory);
Assert.IsFalse(nonExistentFileInfo.IsDirectory());
// Existing, rely on FileAttributes
const string existingDirectory = @"C:\Windows";
var existingDirectoryInfo = new DirectoryInfo(existingDirectory);
Assert.IsTrue(existingDirectoryInfo.IsDirectory());
var existingDirectoryFileInfo = new FileInfo(existingDirectory);
Assert.IsTrue(existingDirectoryFileInfo.IsDirectory());
// Existing, rely on FileAttributes
const string existingFile = @"C:\Windows\notepad.exe";
var existingFileDirectoryInfo = new DirectoryInfo(existingFile);
Assert.IsFalse(existingFileDirectoryInfo.IsDirectory());
var existingFileFileInfo = new FileInfo(existingFile);
Assert.IsFalse(existingFileFileInfo.IsDirectory());
}
这是我们使用的:
using System;
using System.IO;
namespace crmachine.CommonClasses
{
public static class CRMPath
{
public static bool IsDirectory(string path)
{
if (path == null)
{
throw new ArgumentNullException("path");
}
string reason;
if (!IsValidPathString(path, out reason))
{
throw new ArgumentException(reason);
}
if (!(Directory.Exists(path) || File.Exists(path)))
{
throw new InvalidOperationException(string.Format("Could not find a part of the path '{0}'",path));
}
return (new System.IO.FileInfo(path).Attributes & FileAttributes.Directory) == FileAttributes.Directory;
}
public static bool IsValidPathString(string pathStringToTest, out string reasonForError)
{
reasonForError = "";
if (string.IsNullOrWhiteSpace(pathStringToTest))
{
reasonForError = "Path is Null or Whitespace.";
return false;
}
if (pathStringToTest.Length > CRMConst.MAXPATH) // MAXPATH == 260
{
reasonForError = "Length of path exceeds MAXPATH.";
return false;
}
if (PathContainsInvalidCharacters(pathStringToTest))
{
reasonForError = "Path contains invalid path characters.";
return false;
}
if (pathStringToTest == ":")
{
reasonForError = "Path consists of only a volume designator.";
return false;
}
if (pathStringToTest[0] == ':')
{
reasonForError = "Path begins with a volume designator.";
return false;
}
if (pathStringToTest.Contains(":") && pathStringToTest.IndexOf(':') != 1)
{
reasonForError = "Path contains a volume designator that is not part of a drive label.";
return false;
}
return true;
}
public static bool PathContainsInvalidCharacters(string path)
{
if (path == null)
{
throw new ArgumentNullException("path");
}
bool containedInvalidCharacters = false;
for (int i = 0; i < path.Length; i++)
{
int n = path[i];
if (
(n == 0x22) || // "
(n == 0x3c) || // <
(n == 0x3e) || // >
(n == 0x7c) || // |
(n < 0x20) // the control characters
)
{
containedInvalidCharacters = true;
}
}
return containedInvalidCharacters;
}
public static bool FilenameContainsInvalidCharacters(string filename)
{
if (filename == null)
{
throw new ArgumentNullException("filename");
}
bool containedInvalidCharacters = false;
for (int i = 0; i < filename.Length; i++)
{
int n = filename[i];
if (
(n == 0x22) || // "
(n == 0x3c) || // <
(n == 0x3e) || // >
(n == 0x7c) || // |
(n == 0x3a) || // :
(n == 0x2a) || // *
(n == 0x3f) || // ?
(n == 0x5c) || // \
(n == 0x2f) || // /
(n < 0x20) // the control characters
)
{
containedInvalidCharacters = true;
}
}
return containedInvalidCharacters;
}
}
}
最准确的方法是使用 shlwapi.dll 中的一些互操作代码
[DllImport(SHLWAPI, CharSet = CharSet.Unicode)]
[return: MarshalAsAttribute(UnmanagedType.Bool)]
[ResourceExposure(ResourceScope.None)]
internal static extern bool PathIsDirectory([MarshalAsAttribute(UnmanagedType.LPWStr), In] string pszPath);
然后你会这样称呼它:
#region IsDirectory
/// <summary>
/// Verifies that a path is a valid directory.
/// </summary>
/// <param name="path">The path to verify.</param>
/// <returns><see langword="true"/> if the path is a valid directory;
/// otherwise, <see langword="false"/>.</returns>
/// <exception cref="T:System.ArgumentNullException">
/// <para><paramref name="path"/> is <see langword="null"/>.</para>
/// </exception>
/// <exception cref="T:System.ArgumentException">
/// <para><paramref name="path"/> is <see cref="F:System.String.Empty">String.Empty</see>.</para>
/// </exception>
public static bool IsDirectory(string path)
{
return PathIsDirectory(path);
}
public bool IsDirectory(string path) {
return string.IsNullOrEmpty(Path.GetFileName(path)) || Directory.Exists(path);
}
检查路径文件名是否为空字符串,或者目录是否存在。这样您就不会出现文件属性错误,同时仍然为可能的存在故障提供冗余。
我在遇到类似问题时遇到了这个问题,除了当文件或文件夹可能实际上不存在时,我需要检查文件或文件夹的路径是否。上面的答案有一些评论提到它们不适用于这种情况。我找到了一个似乎对我很有效的解决方案(我使用 VB.NET,但您可以根据需要进行转换):
Dim path As String = "myFakeFolder\ThisDoesNotExist\"
Dim bIsFolder As Boolean = (IO.Path.GetExtension(path) = "")
'returns True
Dim path As String = "myFakeFolder\ThisDoesNotExist\File.jpg"
Dim bIsFolder As Boolean = (IO.Path.GetExtension(path) = "")
'returns False
希望这对某人有帮助!
test.txt
,文件可以命名为 test
- 在这些情况下,您的代码将返回不正确的结果
我知道在游戏中太晚了,但我想我还是会分享这个。如果您仅将路径作为字符串使用,那么弄清楚这一点很容易:
private bool IsFolder(string ThePath)
{
string BS = Path.DirectorySeparatorChar.ToString();
return Path.GetDirectoryName(ThePath) == ThePath.TrimEnd(BS.ToCharArray());
}
例如: ThePath == "C:\SomeFolder\File1.txt"
最终会是这样的:
return "C:\SomeFolder" == "C:\SomeFolder\File1.txt" (FALSE)
另一个例子:ThePath == "C:\SomeFolder\"
最终会是这样的:
return "C:\SomeFolder" == "C:\SomeFolder" (TRUE)
这也可以在没有尾随反斜杠的情况下工作: ThePath == "C:\SomeFolder"
最终会是这样的:
return "C:\SomeFolder" == "C:\SomeFolder" (TRUE)
请记住,这只适用于路径本身,而不是路径和“物理磁盘”之间的关系......所以它不能告诉你路径/文件是否存在或类似的东西,但它肯定可以告诉你路径是文件夹还是文件...
System.IO.FileSystemWatcher
,因为当删除目录时,它会发送 c:\my_directory
作为参数,这与删除无扩展名文件 c:\my_directory
时相同。
GetDirectoryName('C:\SomeFolder')
返回 'C:\'
,因此您的最后一个案例不起作用。这不区分没有扩展名的目录和文件。
Path.GetDirectoryName("C:\SomeFolder\SomeSubFolder")
将返回 C:\SomeFolder
。请注意,您自己的 GetDirectoryName 返回示例表明它返回的路径not 以反斜杠结尾。这意味着如果有人在其他地方使用 GetDirectoryName 来获取目录路径,然后将其提供给您的方法,他们将得到错误的答案。
如果你想查找目录,包括那些标记为“隐藏”和“系统”的目录,试试这个(需要 .NET V4):
FileAttributes fa = File.GetAttributes(path);
if(fa.HasFlag(FileAttributes.Directory))
我需要这个,帖子有帮助,这使它归结为一行,如果路径根本不是路径,它只会返回并退出该方法。它解决了上述所有问题,也不需要尾部斜杠。
if (!Directory.Exists(@"C:\folderName")) return;
我明白了,我迟到了 10 年才参加聚会。我面临的情况是,我可以从某些属性中接收文件名或完整文件路径。如果没有提供路径,我必须通过附加另一个属性提供的“全局”目录路径来检查文件是否存在。
就我而言
var isFileName = System.IO.Path.GetFileName (str) == str;
成功了。好的,这不是魔术,但也许这可以节省人们几分钟的时间。由于这只是一个字符串解析,所以带点的目录名称可能会产生误报......
我使用以下内容,它还测试扩展名,这意味着它可以用于测试提供的路径是否是一个文件但一个不存在的文件。
private static bool isDirectory(string path)
{
bool result = true;
System.IO.FileInfo fileTest = new System.IO.FileInfo(path);
if (fileTest.Exists == true)
{
result = false;
}
else
{
if (fileTest.Extension != "")
{
result = false;
}
}
return result;
}
using System;
using System.IO;
namespace FileOrDirectory
{
class Program
{
public static string FileOrDirectory(string path)
{
if (File.Exists(path))
return "File";
if (Directory.Exists(path))
return "Directory";
return "Path Not Exists";
}
static void Main()
{
Console.WriteLine("Enter The Path:");
string path = Console.ReadLine();
Console.WriteLine(FileOrDirectory(path));
}
}
}
使用这篇文章中的选定答案,我查看了评论并相信@ŞafakGür、@Anthony 和 @Quinn Wilson 的信息位,这些信息位引导我找到了我编写和测试的这个改进的答案:
/// <summary>
/// Returns true if the path is a dir, false if it's a file and null if it's neither or doesn't exist.
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
public static bool? IsDirFile(this string path)
{
bool? result = null;
if(Directory.Exists(path) || File.Exists(path))
{
// get the file attributes for file or directory
var fileAttr = File.GetAttributes(path);
if (fileAttr.HasFlag(FileAttributes.Directory))
result = true;
else
result = false;
}
return result;
}
也许对于 UWP C#
public static async Task<IStorageItem> AsIStorageItemAsync(this string iStorageItemPath)
{
if (string.IsNullOrEmpty(iStorageItemPath)) return null;
IStorageItem storageItem = null;
try
{
storageItem = await StorageFolder.GetFolderFromPathAsync(iStorageItemPath);
if (storageItem != null) return storageItem;
} catch { }
try
{
storageItem = await StorageFile.GetFileFromPathAsync(iStorageItemPath);
if (storageItem != null) return storageItem;
} catch { }
return storageItem;
}
在这里聚会很晚,但我发现 Nullable<Boolean>
返回值非常难看 - IsDirectory(string path)
返回 null
不等于没有详细注释的不存在路径,所以我想出了以下:
public static class PathHelper
{
/// <summary>
/// Determines whether the given path refers to an existing file or directory on disk.
/// </summary>
/// <param name="path">The path to test.</param>
/// <param name="isDirectory">When this method returns, contains true if the path was found to be an existing directory, false in all other scenarios.</param>
/// <returns>true if the path exists; otherwise, false.</returns>
/// <exception cref="ArgumentNullException">If <paramref name="path"/> is null.</exception>
/// <exception cref="ArgumentException">If <paramref name="path"/> equals <see cref="string.Empty"/></exception>
public static bool PathExists(string path, out bool isDirectory)
{
if (path == null) throw new ArgumentNullException(nameof(path));
if (path == string.Empty) throw new ArgumentException("Value cannot be empty.", nameof(path));
isDirectory = Directory.Exists(path);
return isDirectory || File.Exists(path);
}
}
这个帮助方法被编写得足够详细和简洁,以便在您第一次阅读它时理解它的意图。
/// <summary>
/// Example usage of <see cref="PathExists(string, out bool)"/>
/// </summary>
public static void Usage()
{
const string path = @"C:\dev";
if (!PathHelper.PathExists(path, out var isDirectory))
return;
if (isDirectory)
{
// Do something with your directory
}
else
{
// Do something with your file
}
}
只需添加一个边缘案例 - “文件夹选择”。在路径中
在我的应用程序中,我收到了最近打开的路径,其中一些路径具有“文件夹选择”。在最后。
一些 FileOpenDialogs 和 WinMerge 添加了“文件夹选择”。到路径(这是真的)。
https://i.stack.imgur.com/VSZ4z.png
但在 Windows 操作系统下的“文件夹选择”。不是建议的文件或文件夹名称(如永远不要这样做 - 握拳)。如此处所述:http://msdn.microsoft.com/en-us/library/aa365247%28VS.85%29.aspx
不要以空格或句点结尾的文件或目录名称。尽管底层文件系统可能支持此类名称,但 Windows shell 和用户界面不支持。但是,可以将句点指定为名称的第一个字符。例如,“.temp”。
所以同时“文件夹选择”。不应该使用,可以。 (惊人的)。
足够的解释 - 我的代码(我很喜欢枚举):
public static class Utility
{
public enum ePathType
{
ePathType_Unknown = 0,
ePathType_ExistingFile = 1,
ePathType_ExistingFolder = 2,
ePathType_ExistingFolder_FolderSelectionAdded = 3,
}
public static ePathType GetPathType(string path)
{
if (File.Exists(path) == true) { return ePathType.ePathType_ExistingFile; }
if (Directory.Exists(path) == true) { return ePathType.ePathType_ExistingFolder; }
if (path.EndsWith("Folder Selection.") == true)
{
// Test the path again without "Folder Selection."
path = path.Replace("\\Folder Selection.", "");
if (Directory.Exists(path) == true)
{
// Could return ePathType_ExistingFolder, but prefer to let the caller known their path has text to remove...
return ePathType.ePathType_ExistingFolder_FolderSelectionAdded;
}
}
return ePathType.ePathType_Unknown;
}
}
这不行吗?
var isFile = Regex.IsMatch(path, @"\w{1,}\.\w{1,}$");
&
运算符将返回一个二进制值,其中仅打开两个操作数中的 (1) 位。在这种情况下,对attr
进行按位与运算,如果目录文件属性位打开,FileAttributes.Directory
值将返回FileAttributes.Directory
的值。请参阅 en.wikipedia.org/wiki/Bitwise_operation 以获得更好的解释。C:\Temp
是指一个名为Temp
的目录还是一个名为Temp
的文件是不明确的。代码是做什么用的?attr.HasFlag(FileAttributes.Directory)
代替。