views:

59

answers:

2

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!

A: 

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
SLaks
Why was this downvoted?
SLaks
Why do people keep giving this answer? Resources are exposed as strongly typed properties within `Properties.Resources`.
Will
@Will: Only if you add it to a ResX file.
SLaks
+1  A: 

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.

Hans Passant
Only if you add it to a .RexX file.
SLaks
@SLaks only if you add it to the project like any normal .NET developer. Its a lot easier to do it that way than to right-click on the file, set it to compile as a resource, then use your pointlessly complex method of getting a resource stream.
Will
@WIll: Correct. ResX files are much easier.
SLaks