vb.net 从列表框中打开文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20426832/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Open file from a listbox
提问by JLM
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?
我正在尝试从 . 打开文件listbox,文件可能是Word、PDF、Excel等。每种文件类型是否需要单独的代码,或者是否有某种方法可以在双击时打开文件?
The listboxpopulates fine through the use of the update buttonI have.
在listbox通过使用更新的填充罚款button我。
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
回答by Steve
In its simplest form you just need to pass the filename to the Process.Start method
在最简单的形式中,您只需要将文件名传递给 Process.Start 方法
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.
另一个问题是您尝试打开的文件类型(扩展名)。填充列表框的方法*.*用于加载 FileInfo。所以每一种文件都被添加到列表框中,如果没有与该扩展名关联的程序,这可能是一个问题。
See more info on Process.Start(string) here
在此处查看有关Process.Start(string) 的更多信息
回答by Shahrukh khan
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)
非常简单的
注意事项:不要编辑(完整路径)
回答by 15ee8f99-57ff-4f92-890c-b56153
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.
我认为您需要的是 Win32 API 函数ShellExecute():它根据注册表中的默认关联“打开”文件。有一篇关于如何从 VB.NET 调用 ShellExecute的知识库文章。

