c# - 在c#中如何区分拖放事件中的文件或文件夹?

标签 c# file drag-and-drop directory

我有一个表单,您可以将文件拖放到其中,我想知道如何让应用程序知道数据是文件还是文件夹。

我的第一次尝试是寻找“.”在数据中,但有些文件夹确实有一个 .在他们中。我也试过执行 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/

相关文章:

c# - 如何更改 Dapper 扩展中的方言?

c# - 从客户端获取修改后的对象并将其与服务器上的原始对象组合

c# - 如何将 SWIG 生成的 C# 文件编译成 .NET DLL?

bash - 如何不敏感地检查文件相似度大小写

c - 如何创建保存从 0000 到 1000 的银行帐号的随机访问文件

angular - 使用 Angular 7 Material CDK 进行嵌套拖放

c# - 每次执行单击事件句柄时都会重置随机数

c++ - 文件处理,复制内容时插入 ÿ 字符

javascript - JQuery UI 拖放在项目到达目的地时显示警报

jquery - 绑定(bind) native html5 dragstart 事件处理程序并使用 jQuery 访问 dataTransfer