VB.net 资源文件读写(EXE)
求教VB.net如何读写EXE附带的资源文件(非.res文件,.exe文件)
一直在网上搜索此类问题答案,却没有可行的,
大多数都只是用Resources.ResourceWriter写res文件。
我有一段VB实现的代码:
Private Declare Function BeginUpdateResource Lib "kernel32" Alias "BeginUpdateResourceA" (ByVal pFileName As String, ByVal bDeleteExistingResources As Boolean) As LongPrivate Declare Function UpdateResource Lib "kernel32" Alias "UpdateResourceA" (ByVal hUpdate As Long, ByVal lpType As Any, ByVal lpName As Any, ByVal wLanguage As Long, lpData As Any, ByVal cbData As Long) As LongPrivate Declare Function EndUpdateResource Lib "kernel32" Alias "EndUpdateResourceA" (ByVal hUpdate As Long, ByVal fDiscard As Boolean) As LongPrivate Function WriteRes(ByVal ResFileName As String, ByVal WriteFileName As String, ByVal ResType As String, ByVal ResID As Long) As BooleanDim VbArrayRes() As Byte '写入内容Dim hUpdate As Long '被写入的目标文件路径Dim Ret As Long '资源句柄Dim ResTypeX As String ResTypeX = StrConv(ResType, vbUpperCase) '将资源标识符 hUpdate = BeginUpdateResource(WriteFileName, False) '打开要写入的目标文件 ReDim VbArrayRes(FileLen(ResFileName) - 1) '计算资源文件大小 Open ResFileName For Binary As #1 '获取资源文件内容 Get #1, , VbArrayRes Close #1 Ret = UpdateResource(hUpdate, ResTypeX, ResID, 0, VbArrayRes(0), UBound(VbArrayRes) + 1) '添加资源 If Ret <> 0 Then WriteRes = True End If '关闭资源更新 Ret = EndUpdateResource(hUpdate, False)End Function
'完整的.Public Class Form1 'VB.NET API声明 Private Declare Function BeginUpdateResource Lib "kernel32" Alias "BeginUpdateResourceA" _ (ByVal pFileName As String, ByVal bDeleteExistingResources As Boolean) As Integer Private Declare Function UpdateResource Lib "kernel32" Alias "UpdateResourceA" _ (ByVal hUpdate As Integer, _ ByVal lpType As String, _ ByVal lpName As Integer, _ ByVal wLanguage As Integer, _ ByRef lpData As Byte, _ ByVal cbData As Integer) As Integer Private Declare Function EndUpdateResource Lib "kernel32" Alias "EndUpdateResourceA" _ (ByVal hUpdate As Integer, ByVal fDiscard As Boolean) As Integer Private Function WriteRes(ByVal ResFileName As String, ByVal WriteFileName As String, ByVal ResType As String, ByVal ResID As Integer) As Boolean Dim VbArrayRes() As Byte '写入内容 Dim hUpdate As Integer '被写入的目标文件路径 Dim Ret As Integer '资源句柄 Dim ResTypeX As String ResTypeX = StrConv(ResType, VbStrConv.Uppercase) '将资源标识符 hUpdate = BeginUpdateResource(WriteFileName, False) '打开要写入的目标文件 ReDim VbArrayRes(FileLen(ResFileName) - 1) '计算资源文件大小 FileOpen(1, ResFileName, OpenMode.Binary) '获取资源文件内容 'UPGRADE_WARNING: Get 已升级到 FileGet 并具有新行为。 FileGet(1, VbArrayRes) FileClose(1) Ret = UpdateResource(hUpdate, ResTypeX, ResID, 0, VbArrayRes(0), UBound(VbArrayRes) + 1) '添加资源 If Ret <> 0 Then WriteRes = True 'Return True End If '关闭资源更新 Ret = EndUpdateResource(hUpdate, False) End Function Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click WriteRes("E:\aaa", "E:\test.exe", "CUSTOM", 101) End SubEnd Class