问题
I'm coding a simple application in C# that allows to add a resource to a .EXE file chosen by me. The problem is that the call to UpdateResource function fails with the error 6, that according to MSDN is InvalidHandle(despite it seems that the call to BeginUpdateResource is successful) (The code is copied and pasted from a bigger file, so if some { lacks, don't care, the code compiles, but doesn't work as expected)
public partial class Form1 : Form
{
[DllImport("kernel32.dll", SetLastError=true)]
static extern bool UpdateResource(IntPtr hUpdate, string lpType, string lpName, ushort wLanguage, IntPtr lpData, uint cbData);
[DllImport("kernel32.dll",SetLastError=true)]
static extern IntPtr BeginUpdateResource(string pFileName, [MarshalAs(UnmanagedType.Bool)]bool bDeleteExistingResources);
[DllImport("kernel32.dll",SetLastError=true)]
static extern bool EndUpdateResource(IntPtr hUpdate, bool fDiscard);
static unsafe void SetRes(string path)
{
IntPtr beginPointer = BeginUpdateResource(path, false);
if (beginPointer != null)
{
MessageBox.Show("Begin works");//This is shown
ushort id = (ushort)Language.MakeLanguageID();
string newMessage = "hello world!";
Byte[] bytes = new ASCIIEncoding().GetBytes(newMessage);
GCHandle bHandle = GCHandle.Alloc(bytes, GCHandleType.Pinned);
IntPtr ptr = bHandle.AddrOfPinnedObject();
bool update = UpdateResource(beginPointer,"FILE", "Test", id,ptr, (uint)bytes.Length);
if (update == true)
{
MessageBox.Show("Update");
EndUpdateResource(beginPointer, false);
}
else
{
MessageBox.Show(Marshal.GetLastWin32Error().ToString()); //It gives error 6
}
}
}
来源:https://stackoverflow.com/questions/10107637/c-sharp-updateresource-function-fails