How i can add an executable file(.exe) to Resources programmatically?

Add an executable file(.exe) to Resources programmatically

Visual Studio 2015 - Visual C# - Windows Forms Application - .NET Framework 4.6.1

What's wrong when i add an executable file(.exe) to resources?

The resource is not displayed with the other resources on the listBox, does not return any error. The names of the resources are loaded correctly in the listbox, the problem if I am not mistaken this when adding the new resource.

    private void button1_Click(object sender, EventArgs e)
    {
        //Add an .exe file to resources
        byte[] xa;

        xa = FileToByteArray(@"C:\Users\" + System.Environment.UserName + @"\Downloads\executable.exe");

        var str = System.Text.Encoding.Default.GetString(xa);
        using (ResXResourceWriter resx = new ResXResourceWriter(@".\Resources.resx"))
        {
            resx.AddResource("myExe", xa);
        }
        //
        //Add the name of existing resources into a listBox
        ResourceManager mgr = Resources.ResourceManager;
        ResourceSet set = mgr.GetResourceSet(CultureInfo.CurrentCulture, true, true);
        foreach (DictionaryEntry o in set){listBox1.Items.Add((string)o.Key);}
        mgr.ReleaseAllResources();
        //
    }

    //Converts a file to a byte array
    public byte[] FileToByteArray(string fileName)
    {
        byte[] buff = null;
        FileStream fs = new FileStream(fileName,FileMode.Open,FileAccess.Read);
        BinaryReader br = new BinaryReader(fs);
        long numBytes = new FileInfo(fileName).Length;
        buff = br.ReadBytes((int)numBytes);
        return buff;
    }

Thank you in advance for your help

Upvotes: 1

Views: 1780

Answers (1)

Michael Gunter
Michael Gunter

Reputation: 12811

A few things:

  • System.Text.Encoding.Default.GetString is a bad way to encode executable bytes. If you need to encode them at all (you probably don't -- see below), use Convert.ToBase64String.
  • AddResource has an overload that takes a byte array. You probably want to use that one instead of encoding your bytes.
  • According to the docs from all the AddResource overloads: "The resource is not written until Generate is called." So call that.

Also, note my comment above. Your FileToByteArray is just a rewrite of the .NET standard File.ReadAllBytes.

Upvotes: 1

Related Questions