VB.Net - How to read in an embedded resource in an assembly

Posted by Blake on 3/31/2015
)

The scenario is that you have an embedded resource in your application or assembly and you want to read it's contents in as text (maybe it's XML, JSON or any other file that you didn't want to include on the file system but wanted it compiled into your assembly).

The first step is to make sure that you click on the file in the solution explorer, view it's properties and change it's "Build Action" to Embedded Resource. Now, all you need to do is read it in. Here's how to do that. I'm going to provide two functions that build off of each other. One will look for the specific resource in the current assembly that you're executing from, the other will allow you to setup and specify the assembly you want.

Note: The "name" of your resource will likely by the root namespace of your assembly plus the name of the file. As an example, it could be "BlakePell.Project1.MyFile.XML" (if the root namespace was BlakePell.Project1).

VB.Net

    ''' 
    ''' Returns a string containing the contents of the specified embedded resource from the executing assembly.
    ''' 
    ''' The name of the file of the embedded resource.  This should include the root namespace preceding the file name.
    ''' A string with the contents of the embedded resource.
    ''' 
    Public Function GetEmbeddedResource(name As String) As String
        Return GetEmbeddedResource(System.Reflection.Assembly.GetExecutingAssembly, name)
    End Function

    ''' 
    ''' Returns a string containing the contents of the specified embedded resource from the provided assembly.
    ''' 
    ''' The System.Reflection.Assembly object you want to get the embedded resource from.
    ''' The name of the file of the embedded resource.  This should include the root namespace preceding the file name.
    ''' A string with the contents of the embedded resource.
    ''' 
    Public Function GetEmbeddedResource(assembly As System.Reflection.Assembly, name As String) As String
        Dim buf As String = ""
        Using s As System.IO.Stream = assembly.GetManifestResourceStream(name)
            Using sr As New System.IO.StreamReader(s)
                buf = sr.ReadToEnd
                sr.Close()
            End Using
            s.Close()
        End Using
        Return buf
    End Function