Jos*_*osh 36 c# windows embed executable
如何在C#Windows窗体应用程序中嵌入外部可执行文件?
编辑:我需要嵌入它,因为它是一个外部的免费控制台应用程序(用C++编写),我从中读取要在我的程序中使用的输出值.嵌入它会更好,更专业.
第二个原因是需要在.NET应用程序中嵌入Flash投影仪文件.
dav*_*v_i 59
最简单的方法,从Will所说的:
编码:
string path = Path.Combine(Path.GetTempPath(), "tempfile.exe");
File.WriteAllBytes(path, MyNamespace.Properties.Resources.MyExecutable);
Process.Start(path);
Run Code Online (Sandbox Code Playgroud)Cha*_*lie 21
下面是一些大致完成此操作的示例代码,减去任何类型的错误检查.另外,请确保要嵌入的程序的许可证允许这种使用.
// extracts [resource] into the the file specified by [path]
void ExtractResource( string resource, string path )
{
Stream stream = GetType().Assembly.GetManifestResourceStream( resource );
byte[] bytes = new byte[(int)stream.Length];
stream.Read( bytes, 0, bytes.Length );
File.WriteAllBytes( path, bytes );
}
string exePath = "c:\temp\embedded.exe";
ExtractResource( "myProj.embedded.exe", exePath );
// run the exe...
File.Delete( exePath );
Run Code Online (Sandbox Code Playgroud)
唯一棘手的部分是为第一个参数获取正确的值ExtractResource.它应该具有"namespace.name"形式,其中namespace是项目的默认命名空间(在Project | Properties | Application | Default namespace下找到它).第二部分是文件的名称,您需要将其包含在项目中(确保将构建选项设置为"嵌入式资源").如果将文件放在目录(例如Resources)下,则该名称将成为资源名称的一部分(例如"myProj.Resources.Embedded.exe").如果遇到问题,请尝试在Reflector中打开已编译的二进制文件,然后查看Resources文件夹.此处列出的名称是您要传递给的名称GetManifestResourceStream.
这可能是最简单的:
byte[] exeBytes = Properties.Resources.myApp;
string exeToRun = Path.Combine(Path.GetTempPath(), "myApp.exe");
using (FileStream exeFile = new FileStream(exeToRun, FileMode.CreateNew))
exeFile.Write(exeBytes, 0, exeBytes.Length);
Process.Start(exeToRun);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
70372 次 |
| 最近记录: |