简体   繁体   中英

Open *.txt with file selector from vb console application

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:

这种事

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 (PS 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.

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM