OK, short (?) story:
Trying to read the folders and subfolders for a given drive using vb.net and VS2022. Many online posts recommend use of Directory.GetDirectories (some going back 20+ years), but it generates errors when a directory is not accessible (access denied) and apparently you can't use TRY CATCH END TRY to fix the issue with .GetDirectories.
Microsoft has a web page that recommends the use of the Directory.EnumerateDirectories method that can be used with TRY CATCH END TRY instead of .GetDirectories.
So this method catches the folders that are not accessible (first problem solved!), but now once I step through the values generated by Directory.EnumerateDirectories, one or more NULL values apparently are stuck in there somewhere. I thought that using TRY CATCH could eliminate this problem, but apparently not.
The code that calls the function is:
Dim directories As List(Of String) = EnumerateDirectories(path)
The function EnumerateDirectories(path) is:
Public Shared Function EnumerateDirectories(path As String) As IEnumerable(Of String)
Try
Dim dirPath As String = "C:\"
Dim dirs As List(Of String) = New List(Of String) _
(Directory.EnumerateDirectories(dirPath, "*", _
SearchOption.AllDirectories))
Return dirs
Catch ex As UnauthorizedAccessException
MessageBox.Show(ex.Message)
Catch ex As ArgumentException
MessageBox.Show(ex.Message)
End Try
End Function
What I have tried:
Two more things to note:
1) VS 2022 does provide the warning:
BC 42105 Function 'EnumerateDirectories' doesn't return a value on all code paths. A null reference exception could occur at run time when the result is used.
Now I did figure out that since this is a function, I need to return something under each CATCH; however, I am not sure what to put there. I *assume* that the function has found a NULL value instead of a folder name (string); somehow, you can tell it to replace the NULL value with a valid string, such as " ". The MessageBox.Show() do not pop up under any CATCH condition.
2) So I use the following code to retrieve the folder names with the following:
Dim directories As List(Of String) = EnumerateDirectories(path)
The code is good up to the point of accessing each value in 'directories'. The following runtime error pops up when I enter a loop to work with each entry in 'directories' (in the main sub, not in the function):
System.NullReferenceException: 'Object reference not set to an instance of an object.'
Overall: I assume this all means that when EnumerateDirectories is doing its function to determine all folders and subfolders for a drive, it is getting a NULL value (or more) instead of a string value. I have tried putting FOR EACH loops in various places to try to replace the NULL value with " ", but to no avail.
Suggestions? Needless to say, I do not make my living as a code developer.