当您使用System.IO.Directory.Exists
时,它只会让您知道它找不到目录,但这可能是因为该目录实际上并不存在,或者因为用户没有足够的对该目录的访问权限。
为了解决这个问题,我们在Directory.Exists
未能获得目录不存在的真正原因后添加了一个辅助测试,我们将其包装到一个全局方法中,用于代替标准Directory.Exists
方法:
''' <summary>
''' This method tests to ensure that a directory actually does exist. If it does not, the reason for its
''' absence will attempt to be determined and returned. The standard Directory.Exists does not raise
''' any exceptions, which makes it impossible to determine why the request fails.
''' </summary>
''' <param name="sDirectory"></param>
''' <param name="sError"></param>
''' <param name="fActuallyDoesntExist">This is set to true when an error is not encountered while trying to verify the directory's existence. This means that
''' we have access to the location the directory is supposed to be, but it simply doesn't exist. If this is false and the directory doesn't exist, then
''' this means that an error, such as a security error, was encountered while trying to verify the directory's existence.</param>
Public Function DirectoryExists(ByVal sDirectory As String, ByRef sError As String, Optional ByRef fActuallyDoesntExist As Boolean = False) As Boolean
' Exceptions are partially handled by the caller
If Not IO.Directory.Exists(sDirectory) Then
Try
Dim dtCreated As Date
' Attempt to retrieve the creation time for the directory.
' This will usually throw an exception with the complaint (such as user logon failure)
dtCreated = Directory.GetCreationTime(sDirectory)
' Indicate that the directory really doesn't exist
fActuallyDoesntExist = True
' If an exception does not get thrown, the time that is returned is actually for the parent directory,
' so there is no issue accessing the folder, it just doesn't exist.
sError = "The directory does not exist"
Catch theException As Exception
' Let the caller know the error that was encountered
sError = theException.Message
End Try
Return False
Else
Return True
End If
End Function