VB.Net If File.Exists Doesn't Return False When File Doesn't Exist

jschlemmer
jschlemmer used Ask the Experts™
on
I am building an application that is supposed to find a file and process it but needs to generate message box alerting user if the file specified doesn't exist.  When I run the program and the file does exist, it works flawlessly.  However, when I run the program and the file doesn't exist, it literally doesn't do anything.  No message box, no errors, absolutely nothing.  It behaves as if it ran through the program successfully and performs the me.close at the end of the script.  Below is the code:

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        For Each q As String In Directory.GetFiles("C:\","InSight_Customized_View_Download*.csv")
            Dim FILE_NAME As String = q
            Dim filename As String = "C:\Error Log\Error Log.txt"
            Dim TextLine As String

            If File.Exists(FILE_NAME) = True Then

               'A bunch of code that executes if file exists.  This runs without any issue.

            Else

                Dim sb As New StringBuilder()
                Using objReader2 As New StreamReader(filename)
                    sb.AppendLine(objReader2.ReadToEnd)
                    sb.AppendLine(Today & vbTab & vbTab & "File Does Not Exist")
                    objReader2.Close()
                End Using

                Dim objWriter As New StreamWriter(filename)
                objWriter.Write(sb.ToString)
                objWriter.Close()

                MsgBox("File Does Not Exist")

            End If
        Next
        Me.Close()
    End Sub


Even though file does not exist, it does not write to error log nor does it generate message box.  It just performs the me.close.
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Have you debugged it to see what happens with the code? It may be having an error and your IDE is not set to Break on errors.
Imran Javed ZiaConsultant Software Engineer - .NET Architect

Commented:
Please use try catch and add some messagebox in catch,
it seems your program is raising some error

 
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        For Each q As String In Directory.GetFiles("C:\", "InSight_Customized_View_Download*.csv")
            Dim FILE_NAME As String = q
            Dim filename As String = "C:\Error Log\Error Log.txt"
            Dim TextLine As String

            If File.Exists(FILE_NAME) = True Then

                'A bunch of code that executes if file exists.  This runs without any issue.

            Else

                'Dim sb As New StringBuilder()
                'Using objReader2 As New StreamReader(filename)
                '    sb.AppendLine(objReader2.ReadToEnd)
                '    sb.AppendLine(Today & vbTab & vbTab & "File Does Not Exist")
                '    objReader2.Close()
                'End Using

                'Dim objWriter As New StreamWriter(filename)
                'objWriter.Write(sb.ToString)
                'objWriter.Close()

                Try
                    ' Following is better approch, it will append data to file 
                    Dim objWriter As New StreamWriter(filename, True)
                    objWriter.Write(Today & vbTab & vbTab & "File Does Not Exist")
                    objWriter.Close()

                    MsgBox("File Does Not Exist")
                Catch ex As Exception
                    MsgBox(ex.Message)
                End Try

            End If
        Next
        Me.Close()
    End Sub

Open in new window

Ron MalmsteadInformation Services Manager

Commented:
Try this instead...

If File.Exists(q) = True Then

Become a CompTIA Certified Healthcare IT Tech

This course will help prep you to earn the CompTIA Healthcare IT Technician certification showing that you have the knowledge and skills needed to succeed in installing, managing, and troubleshooting IT systems in medical and clinical settings.

Ron MalmsteadInformation Services Manager

Commented:
...wait a minute.
A second look at it..

Wouldn't the file always have to exist if it's in the For Each block ?

Certainly you should be using try/catch as well like IJZ stated.
Miguel OzSenior Software Engineer
Top Expert 2009

Commented:
Two issues:
1) Replace this line:
 For Each q As String In Directory.GetFiles("C:\","InSight_Customized_View_Download*.csv")
with:
 Dim files As String() = Directory.GetFiles("C:\","InSight_Customized_View_Download*.csv")
 IF (Files is Nothing) Then
   MsgBox("Files Does Not Exist")
 For Each q As String In files

2) YOu can not use objReader2 As New StreamReader(filename), because the file does not exist, thus it will get an exception. you are better off creating a log file(well known name, InSight_Customized_View.log). Any reason why you need to write the same file with "File Does Not Exist", then file will exist the next time you process it.


Ron MalmsteadInformation Services Manager

Commented:
mas_oz2003,

If there are no files in files string()... it would just go straight to close.

No ?
Fernando SotoRetired
Distinguished Expert 2017

Commented:
Hi jschlemmer;

The Else part of your if statement will only be executed if the program does NOT have file access writes to that file. The Directory.GetFiles("C:\","InSight_Customized_View_Download*.csv") will only return files that do exist and in this case it finds those file in the Root directory of the C drive that starts with the name InSight_Customized_View_Download and has the file extension csv. Using this if statement, If File.Exists(FILE_NAME) = True Then, will return False if the file does NOT exist but in this case they do exist and also if you do not have permissions for the file. Seeming that you state that the else is never executed this can mean that the directory has no files of the type you are looking for or that you have permissions to the files.

Fernando

Author

Commented:
Hi All, thanks for all the tips.  I've tried much of your suggestions and still come up empty.  I've implemented the try catch but still do not receive a message box with any errors.  Please see updated code.  Keep in mind that finding the files and executing the stored procedure and everything all works when the files exist.  But if the folder these files should be in is empty, it simply jumps right to me.close.

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Dim FILE_NAME As String() = Directory.GetFiles("c:\Fedex Integration\", "InSight_Customized_View_Download*.csv")
        Dim filename As String = "c:\Fedex Integration\Error Log\Error Log.txt"
        Dim TextLine As String

        Try

            If FILE_NAME Is Nothing Then

                MsgBox("File Does Not Exist")

                Dim objWriter As New StreamWriter(filename, True)
                objWriter.Write(Today & vbTab & vbTab & "File Does Not Exist")
                objWriter.Close()

            Else

                For Each q As String In FILE_NAME
                    Dim ffile As String = q
                    Dim command As New SqlCommand("Fedex", conn)
                    command.CommandType = CommandType.StoredProcedure
                    Dim dr As SqlDataReader
                    conn.Open()
                    Dim objReader As New System.IO.StreamReader(ffile)
                    objReader.ReadLine()
                    Do While objReader.Peek() <> -1
                        TextLine = objReader.ReadLine()
                        Dim PO As String
                        Dim PrmDate As Date
                        Dim Tstr As String() = TextLine.Split(","c)
                        Dim result As String
                        If Tstr(1) = "" Then
                            PO = "Blank"
                        Else
                            PO = Microsoft.VisualBasic.Right(CStr("000" & Trim(Tstr(1))), 7)

                        End If

                        If IsDate(Tstr(0)) = True Then
                            PrmDate = Tstr(0)
                        Else
                            MsgBox("Invalid Date Field " & Tstr(0).ToString)

                            Dim objWriter3 As New StreamWriter(filename, True)
                            objWriter3.Write(Today & vbTab & vbTab & PO & vbTab & vbTab & "Invalid Est. Delivery Date")
                            objWriter3.Close()
                            Continue Do
                        End If
                        command.Parameters.AddWithValue("@PONumber", PO)
                        command.Parameters.AddWithValue("@PromisedDate", PrmDate)
                        command.Parameters.Add("@Result", SqlDbType.VarChar, 1000).Direction = ParameterDirection.Output
                        dr = command.ExecuteReader
                        dr.Read()
                        result = command.Parameters(2).Value

                        If result <> "Success" Then

                            Dim objWriter1 As New StreamWriter(filename, True)
                            objWriter1.Write(Today & vbTab & vbTab & PO & vbTab & vbTab & result)
                            objWriter1.Close()
                        End If
                        dr.Close()
                        command.Parameters.Clear()
                    Loop
                    objReader.Close()
                    conn.Close()

                    MsgBox("Integration Successful.  File " & ffile & " will be deleted")

                    File.Delete(ffile)
                Next
            End If
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try
        Me.Close()
    End Sub
Actually just found a resolution.  I am doing a directory.getfiles().count and then basing my if statement on whether or not that = 0.  It seems to be working.  Thanks for all your help.  

Author

Commented:
Was able to find a resolution on my own

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial