1

Does anyone have any idea how to initialize (create/access) .NET objects in VBA that require initialization (arguments in the constructor) or static classes? Argument-less constructors can be (more or less) easily initialized, but I had no success initializing classes with arguments, or accessing functions in static classes.

Wanted to use System.IO.File to open a FileStream to be used from System.Security.Cryptography.SHA512Managed Currently I'm feeding the SHA512Managed from byte array, but there is a limitation on the size, also reading the whole file is time consuming.

Current code:

Private Function ReadFileBinary(FileName As String) As Byte()
    Dim f As Long
    f = FreeFile
    Open FileName For Binary As f
    ReDim ReadFileBinary(LOF(f) - 1)
    Get f, , ReadFileBinary
    Close f
End Function

Public Function FileHashSHA256(FileName As String) As String
    Dim binfile() As Byte
    On Error Resume Next
    binfile = ReadFileBinary(FileName)
    If Err Then
        FileHashSHA256 = "FILE ERROR"
        Err.Clear
        Exit Function
    End If
    Set SHA256 = CreateObject("System.Security.Cryptography.SHA256Managed")
    FileHashSHA256 = ToHexString(SHA256.ComputeHash_2(binfile))
    If Err Then
        FileHashSHA256 = "HASH ERROR"
        Err.Clear
    End If
    Set SHA256 = Nothing
End Function

Function ToHexString(rabyt)
    With CreateObject("MSXML2.DOMDocument")
        .LoadXML "<root />"
        .DocumentElement.DataType = "bin.Hex"
        .DocumentElement.nodeTypedValue = rabyt
        ToHexString = Replace(.DocumentElement.text, vbLf, "")
    End With
End Function

I know this could be done differently (e.g. with PowerShell), but the requirement is to do this with PS and .NET compiler disabled.

Rick D.
  • 11
  • 3
  • VBA uses COM. COM doesn't allow parameters during object creation. You can only use interfaces or methods, post creation. However, what limitation on the size are you hitting? Do you have such big files? – Simon Mourier Jun 13 '17 at 13:56
  • There may be disk image files which are bigger than 2GB. – Rick D. Jun 13 '17 at 14:04
  • Also with 'smaller' files this fails already due to memory concern (can allocate the byte array in memory for a ~420 MB file): err.Description - Out of memory – Rick D. Jun 13 '17 at 14:10
  • Are there any .NET helper COM components (Reflection) that would allow bypassing this COM restriction / shortcoming? – Rick D. Jun 13 '17 at 14:15
  • Ok, 420MB *is* big :-) well, I don't see a solution with .NET the way you use it (basically you don't !). I don't see any way to create a .NET's Stream w/o writing a bit of .NET code. You could compile and execute some .NET code on the fly (CodeDom, Roslyn), if that's acceptable with your constraints. – Simon Mourier Jun 13 '17 at 16:32
  • That's sad, thanks for your answers nevertheless. – Rick D. Jun 14 '17 at 12:41

0 Answers0