繁体   English   中英

使用 vb.net 读取 Resorces 文件夹中的 txt 文件

[英]Read txt file in Resorces folder using vb.net

我的目标是将一个 txt 文件存储在 VB.Net 应用程序的 Resources 文件夹中
我使用“项目”>“项目属性”>“资源”>“添加资源”>“添加现有文件”添加了 Dir.txt 文件。
我可以看到该文件并可以使用非常奇怪的几行代码读取它,这些代码涉及使用硬编码路径。 不理想。
我已经包含了一些我已经测试过但没有结果的代码
我可以使用 OpenFileDialog 但我不想 go 钓鱼文件!
只需单击一个按钮并在 RichTextBox 中显示文件
因为该项目有一个 SQLite 我考虑过在创建数据库时将该文件添加到它自己的表中 function

我的两个问题是
如果文件在资源文件夹中,当我使用 Inno Setup package 时,文件会在 exe 文件中吗?
我们能否解释一种更好的方法来完成单击按钮并将文件添加到 RichTextBox?

是的,这些是进口的

Imports System.IO
Imports System.Reflection

  Private Sub btnGetCode_Click(sender As Object, e As EventArgs) Handles btnGetCode.Click
    'Dim openFileDialog As OpenFileDialog = New OpenFileDialog()
    'Dim dr As DialogResult = openFileDialog.ShowDialog()
    'If dr = System.Windows.Forms.DialogResult.OK Then
    '    Dim openPath As String = OpenFileDialog.FileName
    '    rtbViewCode.Text = File.ReadAllText(openPath)
    'End If '' This works but I do not want to go Fishing for the File

    'Why Does this code BELOW FAIL
    'Dim openPath = Path.Combine(Application.StartupPath, "Resource.Dir.txt")
    'rtbViewCode.Text = File.ReadAllText(openPath)

    'Why Does this code BELOW FAIL
    'Dim assmbly As Assembly = Assembly.GetExecutingAssembly()
    'Dim reader As New StreamReader(assmbly.GetManifestResourceStream("frmViewFile.vb.Dir.txt"))
    'rtbViewCode.Text = reader.ReadToEnd


    'While this Code WORKS 
    Dim openP As String = "C:\Users\Dwight\source\repos\TestTwoGrids\TestTwoGrids\Resources\Dir.txt"
    rtbViewCode.Text = File.ReadAllText(openP)

    'End If
End Sub

如果您已经添加了Dir.txt资源文件( Project > Project Properties > Resources > Add Resources > Add Existing File )并分配了一个别名,假设是DirTxt

Resources.resx 示例

唯一剩下要做的就是将其内容插入到 RichBox 中,如下所示:

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    RichTextBox1.Text = My.Resources.DirTxt
End Sub

是的,一旦你编译它,资源就会包含在可执行文件中。

如果这对您有帮助,请将其标记为答案。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM