我有一个表单,您可以将文件拖放到其中,我想知道如何让应用程序知道数据是文件还是文件夹。
我的第一次尝试是寻找“.”在数据中,但有些文件夹确实有一个 .在他们中。我也试过执行 File.Exists 和 Directory.Exists 条件,但它只在当前应用程序路径上搜索,而不是在其他任何地方搜索。
无论如何,我是否可以以某种方式在特定目录中应用 .Exists,或者是否有一种方法可以检查拖入表单的数据类型?
最佳答案
给定字符串形式的路径,您可以使用 System.IO.File.GetAttributes(string path)得到 FileAttributes
枚举,然后检查是否设置了 FileAttributes.Directory
标志。
要在 .NET 4.0 之前的 .NET 版本中检查文件夹,您应该这样做:
FileAttributes attr = File.GetAttributes(path);
bool isFolder = (attr & FileAttributes.Directory) == FileAttributes.Directory;
在较新的版本中,您可以使用 HasFlag
方法来获得相同的结果:
bool isFolder = File.GetAttributes(path).HasFlag(FileAttributes.Directory);
另请注意 FileAttributes
可以提供有关文件/文件夹的各种其他标志,例如:
FileAttributes.Directory
:路径代表一个文件夹FileAttributes.Hidden
: 文件被隐藏FileAttributes.Compressed
:文件已压缩FileAttributes.ReadOnly
: 文件是只读的FileAttributes.NotContentIndexed
:从索引中排除
等等
关于c# - 在c#中如何区分拖放事件中的文件或文件夹?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5893787/