Search code examples
vb.netfilereaderembedded-resourcestreamreader

Read txt file in Resorces folder using vb.net


My goal is to store a txt file in the Resources folder of a VB.Net application
I added the Dir.txt file with Project > Project Properties > Resources > Add Resources > Add Existing File.
I can see the file and can read it using a very odd few lines of code that involve using a hard coded path. Not ideal.
I have included some code that I have tested with NO RESULTS
I can use the OpenFileDialog but I do not want to go Fishing for the file!
Just Click a Button and display the file in the RichTextBox
Because the Project has a SQLite I have considered adding the file to its own table during the DB creation function

My two Questions are
If the file is in the Resources Folder when I package it with Inno Setup will the file be in the exe file?
Can we explain a better way to accomplish clicking a button and adding the file to the RichTextBox?

And YES these are imported

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

Solution

  • If you have already added the Dir.txt resource file (Project > Project Properties > Resources > Add Resources > Add Existing File) and assigned an Alias, let's say DirTxt

    Resources.resx example

    The only thing left to do is to insert its content to the RichBox as follows:

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

    And yes, once you compile it, the resources are embodied inside the executable file.

    If this helps you, please mark it as the answer.