我有一个表单,您可以将文件拖放到其中,我想知道如何让应用程序知道数据是文件还是文件夹.
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.
我的第一次尝试是寻找."在数据中,但有些文件夹确实有一个 .在他们之中.我也尝试过执行 File.Exists 和 Directory.Exists 条件,但它只搜索当前应用程序路径,而不搜索其他任何地方.
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.
无论如何我可以以某种方式将 .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?
将路径作为字符串,您可以使用 System.IO.File.GetAttributes(string path) 获取 FileAttributes
枚举,然后检查 FileAttributes.Directory
标志是否为设置.
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.
要检查 .NET 4.0 之前的 .NET 版本中的文件夹,您应该这样做:
To check for a folder in .NET versions prior to .NET 4.0 you should do:
FileAttributes attr = File.GetAttributes(path);
bool isFolder = (attr & FileAttributes.Directory) == FileAttributes.Directory;
在较新的版本中,您可以使用 HasFlag
方法获得相同的结果:
In newer versions you can use the HasFlag
method to get the same result:
bool isFolder = File.GetAttributes(path).HasFlag(FileAttributes.Directory);
还要注意 FileAttributes
可以提供有关文件/文件夹的各种其他标志,例如:
Note also that FileAttributes
can provide various other flags about the file/folder, such as:
FileAttributes.Directory
:路径代表文件夹FileAttributes.Hidden
:文件被隐藏FileAttributes.Compressed
:文件已压缩FileAttributes.ReadOnly
:文件是只读的FileAttributes.NotContentIndexed
:从索引中排除FileAttributes.Directory
: path represents a folderFileAttributes.Hidden
: file is hiddenFileAttributes.Compressed
: file is compressedFileAttributes.ReadOnly
: file is read-onlyFileAttributes.NotContentIndexed
: excluded from indexing等等
这篇关于c#中如何区分拖放事件中的文件或文件夹?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!