Jerry West wrote:
I am new to VB .NET moving from VB6. I wrote the following code and as a
result I received an error concerning it from the IDE. I don't understand
why I get the message or why that what I am doing is not legal. Here is the
code:
Public Function mP_IsPathExist(ByVal Path As String) As Boolean
On Error Resume Next
Dim myIO As New System.IO.FileInfo(Path)
If (Not myIO.Exists()) Then Dim myIO As New
System.IO.DirectoryInfo(Path)
Return myIO.Exists()
End Function
The error message flags the second Dim statement for myIO. It states:
Variable 'myIO' hides a variable in an enclosing block
I get the sense I cannot reuse the var myIO. Do I have to declare a
completely new var for initializing the DirectoryInfo structure? And what
"enclosing block" does it refer to? The function itself?
You /can/ and /should/ reuse the variable myIO but you're declaring a
whole new variable with the same name (and that is actually scoped to
exist only between the "If" and "End If".
Just assign a new value to the variable (i.e. drop the second Dim).
Public Function mP_IsPathExist(ByVal Path As String) As Boolean
On Error Resume Next
Dim myIO As New System.IO.FileInfo(Path)
If Not myIO.Exists() Then myIO = New
System.IO.DirectoryInfo(Path)
Return myIO.Exists()
End Function
Then ditch the awful one-line If..Then syntax; it's horribly confusing.
Public Function mP_IsPathExist(ByVal Path As String) As Boolean
On Error Resume Next
Dim myIO As New System.IO.FileInfo(Path)
If Not myIO.Exists() Then
myIO = New System.IO.DirectoryInfo(Path)
End If
Return myIO.Exists()
End Function
Then read up about the Imports Statement, to make your coding more concise:
Imports System.IO
Public Function mP_IsPathExist(ByVal Path As String) As Boolean
On Error Resume Next
Dim myIO As New FileInfo(Path)
If Not myIO.Exists() Then
myIO = New DirectoryInfo(Path)
End If
Return myIO.Exists()
End Function
Next, get shot of "On Error" - there are much, /much/ better ways of
doing Error Handling now:
Imports System.IO
Public Function mP_IsPathExist(ByVal Path As String) As Boolean
Try
Dim myIO As New FileInfo(Path)
If Not myIO.Exists() Then
myIO = New DirectoryInfo(Path)
End If
Return myIO.Exists()
Catch ex As Exception
' Do something about the Exception
' ... then ...
Return False
End Try
End Function
Then, read up on the File and Directory classes in the System.IO
Namespace which, IIRC, will be quicker for this particular test:
Imports System.IO
Public Function mP_IsPathExist(ByVal Path As String) As Boolean
Try
If File.Exists( Path ) Then
Return True
ElseIf Directory.Exists( Path )Then
Return True
End If
Return False
Catch ex As Exception
' Do something about the Exception
' ... then ...
Return False
End Try
End Function
HTH,
Phill W.