我正在用 C# 编写一个简单的应用程序,它允许将资源添加到我选择的 .EXE 文件中。问题是对 UpdateResource 函数的调用失败并出现错误 6,根据 MSDN 是 InvalidHandle(尽管对 BeginUpdateResource 的调用似乎是成功的)(代码是从更大的文件中复制和粘贴的,所以如果某些 {缺少, 不用在意, 代码可以编译, 但不能按预期工作)
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
}
}
}