我在最新的视觉工作室社区中构建了一个基本的VB应用程序。这是一个简单的应用程序,可以将文本文件加载到列表框中,然后允许过滤列表,最后复制选定的值。
一切正常,但我很好奇,如果我想将此分发给其他用户,我需要向他们发送文本文件(并且该位置目前是硬编码的)。
必须有更好的方法来实现这一点,我是否需要将文本文件作为某种对象导入到我的项目中,这样它就是项目的一部分而不是文本文件本身?
这是我的代码:
Public Class Form1
Dim MyArray() As String = My.Computer.FileSystem.ReadAllText("C:\Temp\Products.txt").Split(Environment.NewLine)
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
ListBox1.DataSource = MyArray
End Sub
Private Sub ListBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ListBox1.SelectedIndexChanged
TextBox2.Text = ListBox1.SelectedValue
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Clipboard.Clear()
Clipboard.SetText(TextBox2.Text)
End Sub
Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged
Dim FilteredArray(0) As String
Dim ProdName As String
Dim X As Long = 0
ListBox1.DataSource = MyArray
For Each ProdName In ListBox1.Items
If InStr(UCase(ProdName), UCase(TextBox1.Text)) > 0 Then
ReDim Preserve FilteredArray(X)
FilteredArray(X) = ProdName
X = X + 1
End If
Next
ListBox1.DataSource = FilteredArray
End Sub
End Class
感谢任何帮助。
为了完整起见,这是我的最终解决方案:
Imports System.IO
Imports System.Reflection
Public Class Form1
Dim MyArray() As String
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Using sr As StreamReader = New StreamReader(Assembly.GetExecutingAssembly().GetManifestResourceStream("WindowsApplication2.Products.txt"))
MyArray = Split(sr.ReadToEnd(), vbLf)
End Using
ListBox1.DataSource = MyArray
End Sub
Private Sub ListBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ListBox1.SelectedIndexChanged
TextBox2.Text = ListBox1.SelectedValue
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Clipboard.Clear()
Clipboard.SetText(TextBox2.Text)
End Sub
Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged
Dim FilteredArray(0) As String
Dim ProdName As String
Dim X As Long = 0
ListBox1.DataSource = MyArray
For Each ProdName In ListBox1.Items
If InStr(UCase(ProdName), UCase(TextBox1.Text)) > 0 Then
ReDim Preserve FilteredArray(X)
FilteredArray(X) = ProdName
X = X + 1
End If
Next
ListBox1.DataSource = FilteredArray
End Sub
End Class
答案 0 :(得分:1)
我认为存储此类文件的好方法是汇编资源。 将您的文件包含在项目中。将Build Action设置为Embedded Resource,然后该文件将存储在程序集中。 如何从汇编中读取资源文件,您可以在此处找到:How to read embedded resource text file