Tony C
Tony C

Reputation: 568

Using a .txt file Resource in VB

Right now i have a line of code, in vb, that calls a text file, like this:

Dim fileReader As String
    fileReader = My.Computer.FileSystem.ReadAllText("data5.txt")

data5.txt is a resource in my application, however the application doesn't run because it can't find data5.txt. I'm pretty sure there is another code for finding a .txt file in the resource that i'm overlooking, but i can't seem to figure it out. So does anyone know of a simple fix for this? or maybe another whole new line of code? Thanks in advance!

Upvotes: 5

Views: 34357

Answers (3)

Giorgio Barchiesi
Giorgio Barchiesi

Reputation: 6157

First, go to project resources (My Project --> Resources), and drag-and-drop your file, say "myfile.txt", from the file system to the resourses page. Then:

    Imports System.IO
    ...
    Dim stream As New MemoryStream(My.Resources.myfile)
    Dim reader As New StreamReader(stream)
    Dim s As String = reader.ReadToEnd()

Upvotes: 1

Hans Passant
Hans Passant

Reputation: 941455

If you added the file as a resource in the Project + Properties, Resources tab, you'll get its content by using My.Resources:

Dim content As String = My.Resources.data5

Click the arrow on the Add Resource button and select Add Existing File, select your data5.txt file.

Upvotes: 19

SLaks
SLaks

Reputation: 887433

I'm assuming that the file is being compiled as an Embedded Resource.

Embedded Resources aren't files in the filesystem; that code will not work.

You need to call Assembly.GetManifestResourceStream, like this:

Dim fileText As String
Dim a As Assembly = GetType(SomeClass).Assembly
Using reader As New StreamReader(a.GetManifestResourceStream("MyNamespace.data5.txt"))
    fileText = reader.ReadToEnd()
End Using

Upvotes: 4

Related Questions