2011-05-05 49 views
6

我有一個表單,你拖放文件到,我想知道如何讓應用程序知道如果數據是一個文件或文件夾。如何區分c#中的拖放事件中的文件或文件夾?

我的第一次嘗試是尋找一個「。」在數據中,但一些文件夾確實有一個。在他們中。我也試過做File.Exists和Directory.Exists條件,但它只搜索當前應用程序路徑,而不是其他地方。

是否有無論如何我可以以某種方式應用.Exists在特定的目錄或有沒有辦法我可以檢查什麼類型的數據被拖入表單?

+0

WPF或WinForms的? – 2011-05-05 06:58:35

+0

你使用WPF還是WinForms? – 2011-05-05 06:58:54

+2

您的應用程序是否檢索完整路徑或相對路徑? (請給出例子。)如果它只檢索相對路徑,則需要使用Path.Combine與應用程序路徑來獲取完整路徑。 – rwong 2011-05-05 07:00:12

回答

14

以路徑爲字符串,您可以使用System.IO.File.GetAttributes(string path)獲取file's attributes

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

我更喜歡:'bool isFolder = File.GetAttributes(file).HasFlag(FileAttributes.Directory);' – Dan 2013-08-15 21:23:48

+1

+1 @Dan但請記住,這在舊版本的框架中不可用,在這種情況下,上述解決方案是要走的路。 – TimothyP 2013-11-12 05:37:04

+0

@TimothyP在這種情況下,一點邏輯從不會傷害任何人。 ;) – Dan 2013-11-13 14:21:19

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