簡體   English   中英

c#:如何將exe文件嵌入資源?

[英]c#: How to embed exe file into resources?

我用Costura.Fody。

有一個應用程序Test.exe以這種方式運行pocess 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然后運行它?

將應用程序復制到解決方案中的文件夾,例如:Resources或EmbeddedResources等

從解決方案資源管理器中為該應用程序設置“構建操作”為“嵌入式資源”。

現在,應用程序將在構建時嵌入到您的應用程序中。

要在“運行時”訪問它,您需要將其提取到可以執行它的位置。

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>); 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM