This project has moved and is read-only. For the latest updates, please go here.

What is the proper way to check if a folder exists?

Mar 9, 2016 at 10:42 PM
Edited Mar 10, 2016 at 12:50 AM
I need to check if a folder in the Task Scheduler exists off of the root folder. Would I use this code or would you suggest something else?
Public Function doesTaskFolderExist(ByVal strNameOfFolder As String) As Boolean
    Dim taskService As New TaskService
        taskService = Nothing

        Return True
    Catch ex As Exception
        taskService = Nothing

        Return False
    End Try
End Function
Mar 10, 2016 at 4:30 AM
Edited Mar 10, 2016 at 8:57 PM
It is so much easier. Try:
Return TaskService.Instance.GetFolder(strNameOfFolder) IsNot Nothing
You don't need to worry about disposing the TaskFolder instance that may get created since it immediately goes out of scope and the garbage collector will automatically dispose it.

If you know that parent folder and it exists (for example the root folder), a more efficient mode is:
Return TaskService.Instance.RootFolder.SubFolders.Exists(strNameOfChildFolder)
Marked as answer by dahall on 3/9/2016 at 8:35 PM
Mar 10, 2016 at 5:13 AM
Edited Mar 10, 2016 at 5:14 AM
Yeah, the folder is a subfolder of the root folder. I need to make sure that the subfolder of the root folder exists.
Return TaskService.Instance.RootFolder.Exists(strNameOfChildFolder)
That should tell me if the subfolder of the root folder exists? Is there any possibility that the root folder may not exist? I keep getting some reports from some of my users that they keep getting file not found exceptions. Very weird.
Mar 10, 2016 at 3:46 PM
It is impossible for the root folder to 'not exist', so, yes, that line of code will always tell you if that subfolder of root exists. Please note however that subfolders are not supported at all on Windows XP/Server 2003 and earlier.