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

c#: How to embed exe file into resources?

我用Costura.Fody.

有一个应用程序 Test.exe 运行 以这种方式在内部处理Test.exe:

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

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

是否可以嵌入内部Test.exe然后运行呢?

将应用程序复制到您的解决方案中名为以下内​​容的文件夹: 资源或嵌入式资源等

在解决方案资源管理器中为该应用程序将生成操作设置为 'Embedded Resource'。

现在应用程序将在构建时嵌入到您的应用程序中。

为了在 'Run Time' 访问它,您需要将它提取到可以执行它的位置。

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.
            }

        }

一旦你的父应用程序中有了你的字节[],你就可以使用

System.IO.File.WriteAllBytes();

用你想要的文件名将字节数组保存到你的硬盘。

然后您可以使用以下内容启动您的应用程序。 您可能希望使用逻辑来确定该应用程序是否已经存在,如果存在则尝试将其删除。如果它确实存在,只 运行 它而不保存它。

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