C# UpdateResource function fails

二次信任 提交于 2020-01-16 08:07:28

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!