Search code examples
vb.netfilterbackgroundworkeropenfiledialog

OpenFileDialog Filter Option Not Working


Since I put my OpenFileDialog into a BackgroundWorker, the Filter option no longer works.

I use to have this as a button click and it worked fine, with the exception of what every file I opened it wouldn't close the file, hence I added the BackgroundWorker.

Anywho, here's my current code, nothing different from the button click code I had.

Dim OpenFileDialog2 As New OpenFileDialog()

OpenFileDialog2.InitialDirectory = "C:\Temp\Config_Files\"
OpenFileDialog2.Filter = "Configuration Files (*.cfg)|*.cfg"

Is there something I need to add to make this work properly?


Solution

  • I think that you are misunderstanding the advice to use a backgroundworker.
    You should let the OpenFileDialog do its work and grab the cfg file to be processed, then, if you want a faster UI response start the backgroundworker.

    Dim fileToProcess as String = string.Empty
    Using opf As New OpenFileDialog()
        opf.InitialDirectory = "C:\Temp\Config_Files\"
        opf.Filter = "Configuration Files (*.cfg)|*.cfg"
        if opf.ShowDialog() = DialogResult.OK then
            fileToProcess = opf.FileName
        Endif
    End Using
    if fileToProcess <> string.Empty then
        ' Now start you backgroundworker to do its job
    end if
    

    Of course, the user could re-start againg the same code and select again the same file. This could lead to unexpected results. Better to disable the Button/Menu or whatever that start the file selection process till the previous process ends.