Open file from a listbox

a 夏天 提交于 2019-12-25 02:42:38

问题


I'm trying to open files from a listbox, the files could be Word, PDF, Excel, etc. Does there need to be separate code for each file type, or is there some way to just open the file when its double clicked?

The listbox populates fine through the use of the update button I have.

Public Class frmMain

Private Sub ButtonUpdate_Click(sender As Object, e As EventArgs) Handles ButtonUpdate.Click
    Dim folderInfo As New IO.DirectoryInfo("my directory is here")
    Dim arrFilesInFolder() As IO.FileInfo
    Dim fileInFolder As IO.FileInfo
    arrFilesInFolder = folderInfo.GetFiles("*.*")
    For Each fileInFolder In arrFilesInFolder
        ListBox1.Items.Add(fileInFolder.Name)
    Next
End Sub

Private Sub ButtonExit_Click(sender As Object, e As EventArgs) Handles ButtonExit.Click
    Me.Close()
End Sub

Private Sub ListBox1_DoubleClick(sender As Object, e As EventArgs) Handles ListBox1.DoubleClick

End Sub

End Class

回答1:


In its simplest form you just need to pass the filename to the Process.Start method

Private Sub ListBox1_DoubleClick(sender As Object, e As EventArgs) Handles ListBox1.DoubleClick
   Dim fullPath = Path.Combine("YourDirectoryHere", ListBox1.SelectedItem.ToString())
   System.Diagnostics.Process.Start(fullPath)
End Sub

However, this requires that you have saved the directory and recombine it with your file name.

Another problem is the file type (extension) that you try to open. The method that fills the listbox use *.* to load the FileInfo. So every kind of file is added to the listbox and this could be a problem if there is no program associated with that extension.

See more info on Process.Start(string) here




回答2:


I think what you need is the Win32 API function ShellExecute(): It "opens" files according to their default association in the registry. There's a KB article about how to call ShellExecute from VB.NET.




回答3:


Private Sub ListBox1_DoubleClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles ListBox1.DoubleClick
    Dim fullPath = Path.Combine(("Your file path"), ListBox1.SelectedItem.ToString())
    System.Diagnostics.Process.Start(fullPath)

very easy
note:dont edit the (fullpath)



来源:https://stackoverflow.com/questions/20426832/open-file-from-a-listbox

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!