Reputation: 173
I need to use a console application. I would like a file selector to open so the user can select any .txt file. I have looked at OpenFileDialog but as far as I can see that only works for form applications.
This kind of window is what I was looking for:
Upvotes: 0
Views: 2900
Reputation: 20935
Like I said, you should not be using Windows-UI in Console Apps, that said, here's how you do it for your requirement.
I wrote it on my local machine and it works.
Create a new VB.Net Console Project, and Reference to System.Windows.Forms
and paste this entire code in the module1.vb
(P.S. I update it to include @Codexer's recommendation, and also included the error message in the exception handler.)
Imports System.Windows.Forms
Module Module1
<STAThread()> _
Sub Main()
Dim OpenFileDlg as new OpenFileDialog
OpenFileDlg.FileName = "" ' Default file name
OpenFileDlg.DefaultExt = ".txt" ' Default file extension
OpenFileDlg.Filter = "Text Files (*.txt)|*.TXT"
OpenFileDlg.Multiselect = True
OpenFileDlg.RestoreDirectory = True
' Show open file dialog box
Dim result? As Boolean = OpenFileDlg.ShowDialog()
' Process open file dialog box results
for each path in OpenFileDlg.Filenames
Try
System.Diagnostics.Process.Start(Path)
Catch ex As Exception
MsgBox("Error loading the file" & vbCrLf & ex.Message)
End Try
If result = True Then
' Open document
Else
Exit Sub
End If
next
End Sub
End Module
Here's the output.
Upvotes: 3