C#: 如何将exe文件嵌入资源中?

4

我使用Costura.Fody。

有一个名为Test.exe的应用程序,它以以下方式运行进程internalTest.exe:

      ProcessStartInfo prcInfo = new ProcessStartInfo(strpath)
        {
            CreateNoWindow = false,
            UseShellExecute = true,
            Verb = "runas",
            WindowStyle = ProcessWindowStyle.Normal
        };
        var p = Process.Start(prcInfo);

现在我需要向用户提供2个exe文件。

是否可能嵌入internalTest.exe并运行它?


1
应该很容易将文件添加到资源中,并在运行时将其保存为临时文件并正常运行。 - Jens
将文件从资源写入磁盘,然后运行它。这里有一个部分示例可以帮助你:https://dev59.com/kHRA5IYBdhLWcg3wsgBP#10149824 - MartijnK
这是病毒的工作原理。请注意,通常的对策也适用于您的程序。 - Hans Passant
我有一个带有WPF UI(exe)的安装程序,并尝试创建我的引导程序,它将检查是否存在NET 4.5并安装它,然后运行我的安装程序。 - ZedZip
1个回答

5
将应用程序复制到解决方案中的文件夹中,例如:资源(Resources)或嵌入式资源(EmbeddedResources)等。
从解决方案资源管理器中将它的构建操作设置为“嵌入式资源”(Embedded Resource)。
现在,在生成时该应用程序将会被嵌入到你的应用程序中。
为了在“运行时”访问它,你需要将其提取到可以执行的位置。
using (Stream input = thisAssembly.GetManifestResourceStream("Namespace.EmbeddedResources.MyApplication.exe")) 
            {

                byte[] byteData = StreamToBytes(input); 

            }


        /// <summary>
        /// StreamToBytes - Converts a Stream to a byte array. Eg: Get a Stream from a file,url, or open file handle.
        /// </summary>
        /// <param name="input">input is the stream we are to return as a byte array</param>
        /// <returns>byte[] The Array of bytes that represents the contents of the stream</returns>
        static byte[] StreamToBytes(Stream input)
        {

            int capacity = input.CanSeek ? (int)input.Length : 0; //Bitwise operator - If can seek, Capacity becomes Length, else becomes 0.
            using (MemoryStream output = new MemoryStream(capacity)) //Using the MemoryStream output, with the given capacity.
            {
                int readLength;
                byte[] buffer = new byte[capacity/*4096*/];  //An array of bytes
                do
                {
                    readLength = input.Read(buffer, 0, buffer.Length);   //Read the memory data, into the buffer
                    output.Write(buffer, 0, readLength); //Write the buffer to the output MemoryStream incrementally.
                }
                while (readLength != 0); //Do all this while the readLength is not 0
                return output.ToArray();  //When finished, return the finished MemoryStream object as an array.
            }

        }

一旦在父应用程序中获取了应用程序的byte[],您可以使用

System.IO.File.WriteAllBytes();

要将字节数组保存到您想要的文件名的硬盘上,请使用以下方法。

然后,您可以使用以下方式启动应用程序。您可能希望使用逻辑来确定是否已经存在该应用程序,并在存在时尝试删除它。如果已存在,则无需覆盖它,只需运行即可。

System.Diagnostics.Process.Start(<FILEPATH HERE>); 

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接