2016-02-18 39 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>);