2009-11-30 72 views
3

通过函数传递文件的完整路径(例如C:\someFolder\anotherFolder\someXML.xml),确定文件夹是否存在。有没有更聪明/更好/更优雅的方式来做到这一点?这里是我的实现:代码评论:给出完整的文件路径,确定文件夹是否存在?

Private Function FolderExists(ByVal fullPath As String) As Boolean 
    Dim folders() As String = fullPath.Split("\") 
    Dim folderPath As String = "" 
    For i As Integer = 0 To folders.Length - 2 'subtract 2 to avoid appending the filename. 
     folderPath += folders(i) + "\" 
    Next 
    Dim f As New DirectoryInfo(folderPath) 
    Return f.Exists 
End Function 

回答

5

只是使用File.Exists而不是,它接受一个完整的路径。

编辑:对不起,呼叫您的目录变量f困惑我....我相信你能翻译下面的C#代码: -

return Directory.Exists(Path.GetDirectoryName(fullPath)); 

.NET BCL ARM有这方面的东西体面的覆盖面,虽然我当然有更好的参考。 System.IO.PathEnvironment文档可能会很好。

+0

我应该知道有好多是建立在只为这:)谢谢API调用! – Mark 2009-11-30 14:08:50

+0

要翻译C#代码,只需删除分号。 C#是如此罗嗦:) – MarkJ 2009-11-30 17:25:28

0

您可以使用[File.Existshttp://msdn.microsoft.com/en-us/library/system.io.file.exists(VS.71).aspx))

Private Function FolderExists(ByVal fullPath As String) As Boolean 
    return (File.exists(fullPath) 
      And (File.GetAttributes(fullPath) And FileAttributes.Directory)) 
End Function 
+1

-1:他有一个完整的路径,包括文件名,需要分裂它,以确定**目录**是否存在,并且是一个干净利落的方式来做到这一点 – 2009-11-30 14:30:14