简体   繁体   English

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

[英]How do I distinguish a file or a folder in a drag and drop event in c#?

I have a form that you drag and drop files into and I was wondering how can I make the application know if the data is a file or a folder.我有一个表单,您可以将文件拖放到其中,我想知道如何让应用程序知道数据是文件还是文件夹。

My first attempt was to look for a "."我的第一次尝试是寻找一个“。”。 in the data but then some folders do have a.在数据中,但有些文件夹确实有一个。 in them.在他们中。 I've also tried doing a File.Exists and a Directory.Exists condition but then it only searches on the current application path and not anywhere else.我也尝试过执行 File.Exists 和 Directory.Exists 条件,但它只搜索当前应用程序路径,而不搜索其他任何地方。

Is there anyway I can somehow apply the.Exists in a specific directory or is there a way I can check what type of data is dragged into the form?无论如何我可以以某种方式将.Exists应用到特定目录中,或者有没有办法可以检查将哪种类型的数据拖到表单中?

Given the path as a string, you can use System.IO.File.GetAttributes(string path) to get the FileAttributes enum, and then check if the FileAttributes.Directory flag is set.给定路径为字符串,您可以使用System.IO.File.GetAttributes(string path)获取FileAttributes枚举,然后检查是否设置了FileAttributes.Directory标志。

To check for a folder in .NET versions prior to .NET 4.0 you should do:要检查 .NET 4.0 之前的 .NET 版本中的文件夹,您应该执行以下操作:

FileAttributes attr = File.GetAttributes(path);
bool isFolder = (attr & FileAttributes.Directory) == FileAttributes.Directory;

In newer versions you can use the HasFlag method to get the same result:在较新的版本中,您可以使用HasFlag方法获得相同的结果:

bool isFolder = File.GetAttributes(path).HasFlag(FileAttributes.Directory);

Note also that FileAttributes can provide various other flags about the file/folder, such as:另请注意, FileAttributes可以提供有关文件/文件夹的各种其他标志,例如:

  • FileAttributes.Directory : path represents a folder FileAttributes.Directory :路径代表一个文件夹
  • FileAttributes.Hidden : file is hidden FileAttributes.Hidden : 文件被隐藏
  • FileAttributes.Compressed : file is compressed FileAttributes.Compressed :文件被压缩
  • FileAttributes.ReadOnly : file is read-only FileAttributes.ReadOnly : 文件是只读的
  • FileAttributes.NotContentIndexed : excluded from indexing FileAttributes.NotContentIndexed :从索引中排除

etc.等等

if(Directory.Exists(path))
  // then it is a directory
else
  // then it is a file

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM