0

I am trying to copy the contents of an embedded file to a string in Visual Basic using Visual Studio 2013. I already have the resource (Settings.xml) imported and set as an embedded resource. Here is what I have:

Function GetFileContents(ByVal FileName As String) As String
    Dim this As [Assembly]
    Dim fileStream As IO.Stream
    Dim streamReader As IO.StreamReader
    Dim strContents As String
    this = System.Reflection.Assembly.GetExecutingAssembly
    fileStream = this.GetManifestResourceStream(FileName)
    streamReader = New IO.StreamReader(fileStream)
    strContents = streamReader.ReadToEnd
    streamReader.Close()
    Return strContents
End Function

When I try to save the contents to a string by using:

Dim contents As String = GetFileContents("Settings.xml")

I get the following error:

An unhandled exception of type 'System.ArgumentNullException' occurred in mscorlib.dll

Additional information: Value cannot be null.

Which occurs at line:

streamReader = New IO.StreamReader(fileStream)

Nothing else I've read has been very helpful, hoping someone here can tell me why I'm getting this. I'm not very good with embedded resources in vb.net.

Blackwood
  • 4,504
  • 16
  • 32
  • 41
  • 1
    I know this is VB.NET and not C#, but the problem is from .NET side and not language specific, read here: http://stackoverflow.com/a/10773066/3932049 – Camilo Terevinto Jan 08 '16 at 17:06

3 Answers3

0

First check fileStream that its not empty as it seems its contains nothing that's why you are getting a Null exception.

Instead of writing to file test it by using a msgBox to see it its not null.

0

fileStream is Nothing because no resources were specified during compilation, or because the resource is not visible to GetFileContents.

xpda
  • 15,585
  • 8
  • 51
  • 82
0

After fighting the thing for hours, I discovered I wasn't importing the resource correctly. I had to go to Project -> Properties -> Resources and add the resource from existing file there, rather than importing the file from the Solution Explorer. After adding the file correctly, I was able to write the contents to a string by simply using:

Dim myString As String = (My.Resources.Settings)

Ugh, it's always such a simple solution, not sure why I didn't try that first. Hopefully this helps someone else because I saw nothing about this anywhere else I looked.