Search code examples
vb.netopenfiledialog

OpenFileDialog (Cancel/Close) File Not Found Crash


This is my code:

Private Sub HuraButton1_Click(sender As Object, e As EventArgs) Handles HuraButton1.Click
    Dim openFileDialog1 As New OpenFileDialog()
    openFileDialog1.FileName = "Select a Text File..."
    openFileDialog1.Filter = "Text Files (*.txt) | *txt"
    OpenFileDialog1.InitialDirectory = "C:\Users\Public\Desktop\"
    OpenFileDialog1.Title = "Select a Files"
    openFileDialog1.ShowDialog()

    Dim Findstring = IO.File.ReadAllText(openFileDialog1.FileName)
    Dim Lookfor As String = ""
    Dim result = openFileDialog1.ShowDialog()
    If openFileDialog1.FileName = Windows.Forms.DialogResult.Cancel Then
        MsgBox("File Not Found")
    End If
    If Findstring.Contains(Lookfor) Then
        MsgBox("Found")
    Else
        MsgBox("Not Found")
    End If

End Sub

Error:

System.IO.FileNotFoundException: The File'D:\1DesktopFILE\RobeVisualStudio\ShaadyyTool\bin\Debug\Select a Text File' Not Found.

I want to make sure that those who close the "OpenFileDialog1" The app doesn't crash. I Don't know why it doesn't work, Can you write the correct code thanks. Sorry for my eng.


Solution

  • I think this is what you want

    Private Sub HuraButton1_Click(sender As Object, e As EventArgs) Handles HuraButton1.Click
        Dim openFileDialog1 As New OpenFileDialog()
        openFileDialog1.Filter = "Text Files (*.txt) | *txt"
        openFileDialog1.InitialDirectory = "C:\Users\Public\Desktop\"
        openFileDialog1.Title = "Select a Files"
        openFileDialog1.CheckFileExists = True
        If openFileDialog1.ShowDialog() = DialogResult.OK Then
            'file selected now process it 
            Dim Findstring = IO.File.ReadAllText(openFileDialog1.FileName)
            Dim Lookfor As String = ""
            If Findstring.Contains(Lookfor) Then
                MsgBox("Found")
            Else
                MsgBox("Not Found")
            End If
        Else
            'file not selected or user cancelled 
            MsgBox("file not selected")
        End If
    End Sub