.netvb.netpath-manipulation

Code review: Determining whether a folder exists, given the full file path?


With a function being passed a full path to a file, such as C:\someFolder\anotherFolder\someXML.xml, determine whether the folder exists. Is there a smarter/better/more elegant way of doing this? Here is my implementation:

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

Solution

  • just use File.Exists instead, it accepts a full path.

    EDIT: Sorry, calling your directory variable f confused me.... I trust you can translate the following C# code:-

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

    The .NET BCL ARM has decent coverage of this stuff, though I'm sure there's a better reference out there. The System.IO.Path and Environment docs would probably be just fine.