我想確定一個給定的路徑是指向一個文件還是一個目錄。目前我的邏輯很簡單,涉及以下檢查如何確定一個對象是一個文件還是一個文件夾
if (sourcePath.Contains(".")) // then treat this path as a file
上面的問題是文件夾名稱也可能有句號。我希望能夠確定給定路徑是文件的路徑,而不必嘗試實例化文件流類型並嘗試訪問它或類似的文件。
有沒有辦法做到這一點?
在此先感謝
我想確定一個給定的路徑是指向一個文件還是一個目錄。目前我的邏輯很簡單,涉及以下檢查如何確定一個對象是一個文件還是一個文件夾
if (sourcePath.Contains(".")) // then treat this path as a file
上面的問題是文件夾名稱也可能有句號。我希望能夠確定給定路徑是文件的路徑,而不必嘗試實例化文件流類型並嘗試訪問它或類似的文件。
有沒有辦法做到這一點?
在此先感謝
你可以使用File.Exists方法:
如果路徑描述了一個目錄,這 方法返回false
所以:
if (File.Exists(sourcePath))
{
// then treat this path as a file
}
還有Directory.Exists方法和下面的示例中的文檔中給出:
if(File.Exists(path))
{
// This path is a file
ProcessFile(path);
}
else if(Directory.Exists(path))
{
// This path is a directory
ProcessDirectory(path);
}
else
{
Console.WriteLine("{0} is not a valid file or directory.", path);
}
System.IO.File.Exists("yourfilenamehere")
就可以了。如果路徑不是用於文件,這將返回false。如果路徑不存在,它也會返回false,所以要小心。
C#:
public bool IsFolder(string path)
{
return ((File.GetAttributes(path) & FileAttributes.Directory) == FileAttributes.Directory);
}
VB.Net:
Public Function IsFolder(path As String) As Boolean
Return ((File.GetAttributes(path) And FileAttributes.Directory) = FileAttributes.Directory)
End Function
這個函數拋出一個File not found exception
如果該文件不存在。所以你必須抓住它(或者使用Darin Dimitrow的方法)。
Try
Dim isExistingFolder As Boolean = IsFolder(path)
Dim isExistingFile = Not isExistingFolder
Catch fnfEx As FileNotFoundException
'.....
End Try
您可以在.NET 4中使此方法更短:'返回File.GetAttributes(path).HasFlag(FileAttributes.Directory);'。 – 2011-05-14 21:55:36
通過google搜索,我發現這一點:
public bool IsFolder(string path)
{
return ((File.GetAttributes(path) & FileAttributes.Directory) == FileAttributes.Directory);
}
,那麼你可以調用函數如下:
// Define a test path
string filePath = @"C:\Test Folder\";
if (IsFolder(filePath)){
MessageBox.Show("The given path is a folder.");
}
else {
MessageBox.Show("The given path is a file.");
}
var isDirectory = (File.GetAttributes(path) & FileAttributes.Directory) == FileAttributes.Directory;
List<string> RtnList = new List<string>();
foreach (string Line in ListDetails)
{
if (line.StartsWith("d") && !line.EndsWith("."))
{
RtnList.Add(line.Split(' ')[line.Split(' ').Length - 1]);
}
}
這個答案是錯誤地提出這個問題嗎?我沒有看到相關性。 – 2012-09-25 05:40:10
但是你不知道它是否是一個文件夾或它根本不存在... – 2011-05-14 21:24:21
@Erno,那是真的,但如果OP的意圖是操縱這個文件,那麼這可能是一個安全檢查。另外,如果文件和目錄都不存在,則不可能說它是文件還是目錄。 – 2011-05-14 21:31:03
@Darin:這取決於他從哪裏獲得源路徑。 – 2011-05-14 21:34:22