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 fil开发者_StackOverflowes 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.
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?
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.
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;
In newer versions you can use the HasFlag
method to get the same result:
bool isFolder = File.GetAttributes(path).HasFlag(FileAttributes.Directory);
Note also that FileAttributes
can provide various other flags about the file/folder, such as:
FileAttributes.Directory
: path represents a folderFileAttributes.Hidden
: file is hiddenFileAttributes.Compressed
: file is compressedFileAttributes.ReadOnly
: file is read-onlyFileAttributes.NotContentIndexed
: excluded from indexing
etc.
if(Directory.Exists(path))
// then it is a directory
else
// then it is a file
精彩评论