从列表框打开文件 [英] Open file from a listbox
问题描述
我试图从列表框
打开文件,这些文件可能是 Word , PDF ,< Excel> 等。是否需要为每个文件类型单独的代码,或者有什么方法可以打开文件时双击?
列表框
通过使用更新按钮
来填充。
公共类frmMain
Private Sub ButtonUpdate_Click(sender As Object,e As EventArgs)处理ButtonUpdate.Click
Dim folderInfo As新的IO.DirectoryInfo(我的目录在这里)
Dim arrFilesInFolder()作为IO.FileInfo
昏暗的fileInFolder作为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作为EventArgs)处理ButtonExit.Click
Me.Cl ose()
End Sub
Private Sub ListBox1_DoubleClick(sender As Object,e As EventArgs)Handles ListBox1.DoubleClick
End Sub
End Class
将文件名传递给Process.Start方法
$ b $ pre $ Private $ 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
$ c但是,这需要您保存目录并将其与您的文件名重新组合。
另一个问题是您尝试打开的文件类型(扩展名)。填充列表框的方法使用 *。*
加载FileInfo。所以每一种文件都被添加到列表框中,如果没有与该扩展相关的程序,这可能是一个问题。
更多关于 Process.Start(string)here
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
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
这篇关于从列表框打开文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!