VB.NET UpdateResource始终是资本并且添加资源,而不是更新

时间:2013-10-05 12:26:21

标签: .net vb.net winapi resources native

我想知道为什么我的updateresource无效。它始终是资本,并且不更新/替换资源,只添加一个。

这是我在VB.NET中的代码

Imports System.Runtime.InteropServices

Public Class Form1

Private Sub btnStart_Click(sender As Object, e As EventArgs) Handles btnStart.Click
    Dim strMiniConfig As String
    strMiniConfig = TextBox1.Text

    Dim encoder As New System.Text.UnicodeEncoding()

    WriteResource("UpdateMyRes.exe", encoder.GetBytes(strMiniConfig))

    MsgBox("Resources are now updated.", vbOKOnly + MsgBoxStyle.Information)

End Sub


<DllImport("kernel32.dll", SetLastError:=True, CharSet:=CharSet.Unicode)> _
Private Shared Function UpdateResource(ByVal hUpdate As IntPtr, ByVal lpType As String, ByVal lpName As String, ByVal wLanguage As UShort, ByVal lpData As IntPtr, ByVal cbData As UInteger) As Boolean
End Function
<DllImport("kernel32.dll", SetLastError:=True, CharSet:=CharSet.Unicode)> _
Private Shared Function BeginUpdateResource(ByVal pFileName As String, <MarshalAs(UnmanagedType.Bool)> ByVal bDeleteExistingResources As Boolean) As IntPtr
End Function
<DllImport("kernel32.dll", SetLastError:=True, CharSet:=CharSet.Unicode)> _
Private Shared Function EndUpdateResource(ByVal hUpdate As IntPtr, ByVal fDiscard As Boolean) As Boolean
End Function

Public Function WriteResource(ByVal filename As String, ByVal bytes As Byte()) As Boolean
    Try
        Dim handle As IntPtr = BeginUpdateResource(filename, False)
        Dim file1 As Byte() = bytes
        Dim fileptr As IntPtr = ToPtr(file1)
        Dim res As Boolean = UpdateResource(handle, "RCData", "CONFIG", 1, fileptr, System.Convert.ToUInt16(file1.Length))
        EndUpdateResource(handle, False)
    Catch ex As Exception
        Return False
    End Try
    Return True

End Function

Private Function ToPtr(ByVal data As Object) As IntPtr
    Dim h As GCHandle = GCHandle.Alloc(data, GCHandleType.Pinned)
    Dim ptr As IntPtr
    Try
        ptr = h.AddrOfPinnedObject()
    Finally
        h.Free()
    End Try
    Return ptr

End Function
End Class

这应该替换RCData \ CONFIG中的资源,但它总是添加名为RCDATA \ CONFIG的资源?这是为什么?

以下是C ++中的相同代码:

WCHAR * newD = L"I am updated resource at the RCData\CONFIG";
HANDLE hUpdate = BeginUpdateResourceW(L"Stub.exe", false);
UpdateResourceW(hUpdate, MAKEINTRESOURCEW(10), L"CONFIG", 1, newD, wcslen(newD)*2);
EndUpdateResource(hUpdate, false);

1 个答案:

答案 0 :(得分:0)

现在通过使用不同的API修复它。

当我可以的时候关闭它。