2016-02-18 37 views
3

我使用Costura.Fody。c#:如何將exe文件嵌入資源?

有一個應用程序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然後運行它?

+1

應該直接將文件添加到資源,並在運行時將其保存爲臨時文件並正常運行。 – Jens

+0

將文件從資源寫入光盤,然後運行它。以下是部分示例,可以幫助您:http://stackoverflow.com/a/10149824/390421 – MartijnK

+0

這是病毒如何工作的。期望通常的反制措施也適用於您的計劃。 –

回答

3

應用程序複製到被稱爲像您的解決方案中的文件夾: 資源或EmbeddedResources等

設置生成操作爲從Solution Explorer該應用程序「嵌入的資源」。

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

爲了在'運行時'訪問它,你需要將它提取到你可以執行它的位置。

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