Search code examples
.netvb.netbinaryfilesembedded-resourcemy.resources

How can I write a subroutine to write an embedded binary resource to a file?


I have a resource file embedded within my VB.NET 2019 project that with a button click, I would like to copy to the desktop. I tried to do this with a private sub so I could reuse the function but I cannot get it to work. The files are binary files.

Private Sub CreateBinary(ByVal objResource As Object, ByVal FullPath As String)
    Dim WriteBinary As BinaryWriter
    Try
        WriteBinary = New BinaryWriter(FullPath)
        WriteBinary.Write(objResource)
        WriteBinary.Close()
    Catch
    End Try
End Sub

Which I want to then call from the following:

CreateBinary(My.Resources.user32, My.Computer.FileSystem.SpecialDirectories.Desktop)

I can't seem to find anything that works. I have a similar function with other resource files that are text files that uses StreamWriter. All this really confirms is my binary files are embedded properly as resource files since they are all in the same place in my project.


Solution

  • The first thing to check on is how the resource is defined in the appropriate resx file (for VB, I think it will be in "My Project"). It should look something like this:

    <value>[path to source file];System.Byte[], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
    

    If so, then the resource class provided by the designer will give you back a byte array, which is trivial to write to a file:

    System.IO.File.WriteAllBytes(filename, My.Resources.FileResource)
    

    (where "FileResource" is the name of the resource)