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

Time:06-07

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.

CodePudding user response:

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)

CodePudding user response:

Try the following

Imports System.IO

Module ResourceExtensions
    <Runtime.CompilerServices.Extension()>
    Public Sub FileSave(BytesToWrite() As Byte, FileName As String)

        If File.Exists(FileName) Then
            File.Delete(FileName)
        End If

        Dim FileStream As New FileStream(FileName, FileMode.OpenOrCreate)
        Dim BinaryWriter As New BinaryWriter(FileStream)

        BinaryWriter.Write(BytesToWrite)
        BinaryWriter.Close()
        FileStream.Close()

    End Sub
End Module

Let's say the file in resource is Customers.xlsx, here I extract to C:\ExcelFiles. The path must exists.

Public Class Form1
    Private Sub ExtractButton_Click(sender As Object, e As EventArgs) _
        Handles ExtractButton.Click

        Dim exportFileName = "C:\ExcelFiles\Customers.xlsx"
        My.Resources.Customers.FileSave(exportFileName)

    End Sub
End Class
  • Related