0

I have a part of my code that's supposed to extract an embedded source to a temp folder.

Sub Main()
    Dim temp As String
    temp = Path.GetTempPath()
    Console.WriteLine(temp)
    ExtractResourceToDisk("FileExtract.file.exe", temp & "file.exe")
    Process.Start(temp & "file.exe")
End Sub

    Public Function ExtractResourceToDisk(ByVal ResourceName As String, ByVal FileToExtractTo As String) As Boolean

    Dim s As System.IO.Stream = System.Reflection.Assembly.GetExecutingAssembly.GetManifestResourceStream(ResourceName)
    Dim ResourceFile As New System.IO.FileStream(FileToExtractTo, IO.FileMode.Create)

    Console.WriteLine(s.Length)

    Dim b(s.Length) As Byte

    s.Read(b, 0, s.Length)
    ResourceFile.Write(b, 0, b.Length - 1)
    ResourceFile.Flush()
    ResourceFile.Close()

    ResourceFile = Nothing
End Function

However, I'm getting an "Object reference not set to an instance of an object" error on the line "Dim b(s.Length) As Byte" when I try to run.

Cœur
  • 37,241
  • 25
  • 195
  • 267
John
  • 15
  • 2

3 Answers3

0
     Public Function ExtractResourceToDisk(ByVal ResourceName As String, ByVal FileToExtractTo As String) As Boolean


'New keyword is needed for creating  instance
        Dim s As New System.IO.Stream = System.Reflection.Assembly.GetExecutingAssembly.GetManifestResourceStream(ResourceName) 
        Dim ResourceFile As New System.IO.FileStream(FileToExtractTo, IO.FileMode.Create)

        Console.WriteLine(s.Length)

        Dim b(s.Length) As Byte
Dandy
  • 467
  • 1
  • 10
  • 33
0

Because Dim b(s.Length) As Byte throws the null reference exception it follows that s is null, and thus that:

System.Reflection.Assembly.GetExecutingAssembly.GetManifestResourceStream(ResourceName)

returns null (Nothing).

Double check the value of ResourceName and take a look at the accepted answer to: GetManifestResourceStream returns NULL

Community
  • 1
  • 1
tolanj
  • 3,651
  • 16
  • 30
0

s.Length is return Null so the error occurs.

FYI as i attached tested snippets

Dim Str As String // if initilize Str variable it not shows the error

Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
    Dim Test(Str.Length) As Byte
    Test(0) = 123
End Sub