vb.net - 如何将自定义文本文件添加到 Visual Studio 项目?

标签 vb.net visual-studio

我正在构建一个打字应用程序,并且想将包含各种常用单词的文本文件添加到项目中,以便稍后读取。但是,当我进入“项目”->“添加现有项目”时,只有将 VB 代码文件添加到项目的选项。有没有办法将文本文件添加到项目中,或者我必须在运行时从文件导入数据?

最佳答案

项目资源 (Resx) 版本:

此版本对于您的示例来说稍微更容易使用!

  • 右键单击您的项目
  • 选择属性
  • 转到资源部分
  • 您将在资源部分的左上角看到一个下拉列表,如下面的屏幕截图所示。
  • 从下拉菜单中选择"file"。
  • 点击“添加资源”按钮。
  • 将显示“选择文件”对话框。
  • 选择您的文件
  • 保存您的项目

Resx Resources

现在要访问此文件,只需使用类似...

Dim content As String = My.Resources.mytextfile

注意:您不需要扩展,并且这也将是强类型的!

嵌入式资源版本:

  • 右键单击您的项目。
  • 转到“添加”->“现有项目”。
  • 右下角将有一个下拉菜单(位于文件名旁边)。
  • 选择“所有文件 (*.*)”
  • 浏览到您的文件所在位置。
  • 添加文件。

Select All Files

添加文件后,在解决方案资源管理器窗口中选择文件将允许您选择其“构建操作”。您可以从选项中选择内容或嵌入资源。

  • Content: Allows you to retrieve a file (in same dir as assembly) as a stream via Application.GetContentStream( uri ). For this method to work, it needs a AssemblyAssociatedContentFile custom attribute which VS graciously adds when you mark a file as "Content"
  • Embedded resource: embeds the file in an exclusive assembly manifest resource.

摘自; https://stackoverflow.com/a/145769/1305169

如果您选择嵌入资源,则要读取文本文件,您可以使用以下代码:

Dim executing_assembly As System.Reflection.Assembly = _
    Me.GetType.Assembly.GetEntryAssembly()

' Get our namespace.
Dim my_namespace As String = _
    executing_assembly.GetName().Name.ToString()

' Load a text file.
Dim text_stream As Stream = _
    executing_assembly.GetManifestResourceStream(my_namespace _
    + ".text1.txt")
If Not (text_stream Is Nothing) Then
    Dim stream_reader As New StreamReader(text_stream)
    Label1.Text = stream_reader.ReadToEnd()
    stream_reader.Close()
End If

取自:http://www.vb-helper.com/howto_net_embedded_resources.html

关于vb.net - 如何将自定义文本文件添加到 Visual Studio 项目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14591429/

相关文章:

vb.net - 是否有用于在 VB.NET 中进行开发的 BDD/TDD 工具?

vb.net - 具有自定义身份验证和 ClaimsIdentity 的 MVC 5 SecurityStampValidator

.net - 多列列表框

VB Net 中的 XML 解析

visual-studio - 运行 Web Developer Express 时如何清除 IE 缓存?

c++ - .net 中的私有(private)成员?

.net - 无法在 .Net 应用程序中复制文件

c# - 用多个 byte[] 填充一个 byte[]

.net - 如何修复 'Resources'不是 'My'的成员

visual-studio - Visual Studio 2010 中的成员/方法组合框发生了什么变化?