Using VB on Windows 11 (64bits) I have a windows form application containing two buttons. One shows the OpenFileDialog and the other opens on Excel workbook with a name based on the current date (i.e. 230701_Data.xlsx). That worked but at some point something must have changed that caused that both methods of opening a file do not open the file(s) anymore eventhough no errors or exceptions are shown and the filenames are correct and the files can be opened from Explorer. The file based on the date is even read and written from the program!
What could be causing that the files can't be shown anymore?
Public Function selectFile()
Dim fileInUse As String = My.Settings.fileInUse.Trim()
Dim selectedFile As String = ""
Dim ofd As OpenFileDialog = New OpenFileDialog
ofd.DefaultExt = "xlsx"
ofd.FileName = "" '// System.IO.Path.GetFileName(fileInUse)
ofd.InitialDirectory = Path.GetDirectoryName(fileInUse)
ofd.CheckFileExists = True
ofd.Multiselect = False
ofd.FilterIndex = 1
ofd.Filter = "All Files (*.*) |*.*|Excel Files (*.xl*)|*.xl*|CSV Files (*.csv)|*.csv|Text Files (*.txt)|*.txt|Visual Studio Files(*.vb)|*.vb|TradingView Scripts(*.pine)|*.pine|PDF Files (*.pdf)|*.pdf"
While selectedFile = ""
If ofd.ShowDialog = DialogResult.OK Then
If ofd.FileName = My.Settings.fileInUse Then
MsgBox("The selected file is in use" + Environment.NewLine + fileInUse + Environment.NewLine + "cannot be opened")
Else
selectedFile = ofd.FileName
End If
Try
ofd.OpenFile()
Catch ex As Exception
MsgBox("OpenFile failed Error= " & ex.Message)
End Try
Else
Exit While '// Must allow to exit without choosing a file
End If
End While
Return selectedFile
End Function
This is a perfect example of why you should ALWAYS read the relevant documentation. If you are posting a question here then you should already have done so. If you had done that then your problem would be obvious.
The documentation for the
OpenFileDialog.OpenFilemethod makes it clear that the method returns aStreamand it's from thatStreamthat YOU are supposed to read the data the file contains. You are just ignoring the returnedStreamso why would anything useful happen?If what you actually want to happen is for the file to be opened in its default application, e.g. Excel for an XLSX file, then what you actually need to do is call
Process.Startand pass the file path as an argument.Actually, it occurs to me that maybe you are trying to open the file elsewhere, in code that you haven't shown us. In that case, it's bad that you haven't shown us code that's relevant to the issue. If the file is failing to open elsewhere then that would likely be caused by the fact that you are opening it in this code but not closing it. If it's opened exclusively here, obviously it can't be opened elsewhere. If you want to open it here, use the
Streamyou open. If you don't want that then don't open it here in the first place.