在 C# 程序中嵌入外部可执行文件 [英] Embedding an external executable inside a C# program

查看:80
本文介绍了在 C# 程序中嵌入外部可执行文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 C# Windows 窗体应用程序中嵌入外部可执行文件?

How do I embed an external executable inside my C# Windows Forms application?

我需要嵌入它,因为它是一个外部免费控制台应用程序(用 C++ 制作),我从中读取了要在我的程序中使用的输出值.嵌入它会更好,更专业.

I need to embed it because it's an external free console application (made in C++) from which I read the output values to use in my program. It would be nice and more professional to have it embedded.

第二个原因是需要在 .NET 应用程序中嵌入 Flash 投影仪文件.

Second reason is a requirement to embed a Flash projector file inside a .NET application.

推荐答案

以下是一些示例代码,可以大致完成此操作,无需进行任何类型的错误检查.另外,请确保要嵌入的程序的许可允许此类使用.

Here is some sample code that would roughly accomplish this, minus error checking of any sort. Also, please make sure that the license of the program to be embedded allows this sort of use.

// 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:	empembedded.exe";
ExtractResource( "myProj.embedded.exe", exePath );
// run the exe...
File.Delete( exePath );

唯一棘手的部分是为 ExtractResource 的第一个参数获取正确的值.它应该具有namespace.name"的形式,其中 namespace 是您项目的默认命名空间(在 Project | Properties | Application | Default namespace 下找到它).第二部分是文件的名称,您需要将其包含在您的项目中(确保将构建选项设置为嵌入式资源").如果你把文件放在一个目录下,例如资源,然后该名称成为资源名称的一部分(例如myProj.Resources.Embedded.exe").如果遇到问题,请尝试在 Reflector 中打开已编译的二进制文件并查看 Resources 文件夹.此处列出的名称是您将传递给 GetManifestResourceStream 的名称.

The only tricky part is getting the right value for the first argument to ExtractResource. It should have the form "namespace.name", where namespace is the default namespace for your project (find this under Project | Properties | Application | Default namespace). The second part is the name of the file, which you'll need to include in your project (make sure to set the build option to "Embedded Resource"). If you put the file under a directory, e.g. Resources, then that name becomes part of the resource name (e.g. "myProj.Resources.Embedded.exe"). If you're having trouble, try opening your compiled binary in Reflector and look in the Resources folder. The names listed here are the names that you would pass to GetManifestResourceStream.

这篇关于在 C# 程序中嵌入外部可执行文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆