Maury Markowitz
Maury Markowitz

Reputation: 9283

Do GetManifestResourceStream() items have to be in Resources?

I copied a file, vbaProject.bin into the root of my VS.net project (I want it to be highly visible, not in a subfolder). I selected it and set the Build Action to Embedded Resource. Then I did this in my code...

App = System.Reflection.Assembly.GetExecutingAssembly()
Ans = App.GetManifestResourceStream("vbaProject.bin")

Ans is always Nothing. GetManifestResourceStream is a bit of a black box to me, can if find this resource in the "root"? If so, do I have the name correct, or do I need some sort of path here?

UPDATE: Following Michael's suggestion, I did this:

App = System.Reflection.Assembly.GetExecutingAssembly()
Ans = App.GetManifestResourceStream(App.GetName().ToString().Split(","c)(0) & ".vbaProject.bin")

Is that a safe solution?

Upvotes: 0

Views: 608

Answers (1)

TnTinMn
TnTinMn

Reputation: 11801

If you wish to rely on the behavior of Visual Studio, then you could do something like this:

Dim asm As Assembly = Assembly.GetExecutingAssembly
Dim firstType As Type = asm.GetTypes(0)
Dim rootNamespace As String = firstType.Namespace
Dim myFileName As String = "something.bin"
Dim strm As IO.Stream = asm.GetManifestResourceStream(rootNamespace & "." & myFileName)

This relies on the behavior of Visual Studio to pre-pend the root namespace to the embedded file's name.

A better solution is to modify the ProjectName.vbproj file (MS Build file) to specify the exact name you want to use. You should find an <ItemGroup> that contains the directive to embed the file.

  <ItemGroup>
    <EmbeddedResource Include="DirectoryPath\something.bin" />
  </ItemGroup>

change the above to specify the LogicalName tag that will provide the name to use.

  <ItemGroup>
    <EmbeddedResource Include="DirectoryPath\something.bin">
      <LogicalName>something.bin</LogicalName>
    </EmbeddedResource>
  </ItemGroup>

Close Visual Studio and edit the ProjectName.vbproj in a text editor. This change will be preserved when you load the project in Visual Studio.

With this change, now you can obtain the stream like this:

Dim myFileName As String = "something.bin"
Dim strm As IO.Stream = asm.GetManifestResourceStream(myFileName)

Upvotes: 2

Related Questions