在 C# 程序中嵌入外部可执行文件

发布于 2024-07-18 07:55:57 字数 173 浏览 4 评论 0原文

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

编辑:我需要嵌入它,因为它是一个外部免费控制台应用程序(用 C++ 编写),我从中读取要在程序中使用的输出值。 如果能嵌入它就更好了,也更专业。

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

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

Edit: 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.

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

格子衫的從容 2024-07-25 07:55:57

最简单的方法,从 Will 所说的开始

  1. 使用 Resources.resx 添加 .exe
  2. 编码:

    字符串路径 = Path.Combine(Path.GetTempPath(), "tempfile.exe");   
      File.WriteAllBytes(路径, MyNamespace.Properties.Resources.MyExecutable); 
      进程.开始(路径); 
      

Simplest way, leading on from what Will said:

  1. Add the .exe using Resources.resx
  2. Code this:

    string path = Path.Combine(Path.GetTempPath(), "tempfile.exe");  
    File.WriteAllBytes(path, MyNamespace.Properties.Resources.MyExecutable);
    Process.Start(path);
    
九命猫 2024-07-25 07:55:57

下面是一些示例代码,可以大致完成此任务,减去任何类型的错误检查。 另外,请确保要嵌入的程序的许可证允许此类使用。

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

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

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

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.

彡翼 2024-07-25 07:55:57

只需将其添加到您的项目并将构建选项设置为“嵌入式资源”

Just add it to your project and set the build option to "Embedded Resource"

温馨耳语 2024-07-25 07:55:57

这可能是最简单的:

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

This is probably the simplest:

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);
浪推晚风 2024-07-25 07:55:57

可执行文件是托管程序集吗? 如果是这样,您可以使用 ILMerge 将该程序集与您的程序集合并。

Is the executable a managed assembly? If so you can use ILMerge to merge that assembly with yours.

來不及說愛妳 2024-07-25 07:55:57

这是我的版本:
将文件作为现有项目添加到项目中,将文件的属性更改为“嵌入资源”

要将文件动态提取到给定位置:(此示例不测试位置的写入权限等)

    /// <summary>
    /// Extract Embedded resource files to a given path
    /// </summary>
    /// <param name="embeddedFileName">Name of the embedded resource file</param>
    /// <param name="destinationPath">Path and file to export resource to</param>
    public static void extractResource(String embeddedFileName, String destinationPath)
    {
        Assembly currentAssembly = Assembly.GetExecutingAssembly();
        string[] arrResources = currentAssembly.GetManifestResourceNames();
        foreach (string resourceName in arrResources)
            if (resourceName.ToUpper().EndsWith(embeddedFileName.ToUpper()))
            {
                Stream resourceToSave = currentAssembly.GetManifestResourceStream(resourceName);
                var output = File.OpenWrite(destinationPath);
                resourceToSave.CopyTo(output);
                resourceToSave.Close();
            }
    }

Here's my version:
Add the file to the project as an existing item, change the properties on the file to "Embedded resource"

To dynamically extract the file to a given location: (this example doesn't test location for write permissions etc)

    /// <summary>
    /// Extract Embedded resource files to a given path
    /// </summary>
    /// <param name="embeddedFileName">Name of the embedded resource file</param>
    /// <param name="destinationPath">Path and file to export resource to</param>
    public static void extractResource(String embeddedFileName, String destinationPath)
    {
        Assembly currentAssembly = Assembly.GetExecutingAssembly();
        string[] arrResources = currentAssembly.GetManifestResourceNames();
        foreach (string resourceName in arrResources)
            if (resourceName.ToUpper().EndsWith(embeddedFileName.ToUpper()))
            {
                Stream resourceToSave = currentAssembly.GetManifestResourceStream(resourceName);
                var output = File.OpenWrite(destinationPath);
                resourceToSave.CopyTo(output);
                resourceToSave.Close();
            }
    }
溺ぐ爱和你が 2024-07-25 07:55:57
  1. 将文件添加到 VS 项目
  2. 标记为“嵌入式资源”-> 文件属性
  3. 使用名称来解析:[程序集名称].[嵌入式资源名称],例如“MyFunkyNTServcice.SelfDelete.bat”

您的代码存在资源错误(文件句柄未释放!),请更正为:

public static void extractResource(String embeddedFileName, String destinationPath)
    {
        var currentAssembly = Assembly.GetExecutingAssembly();
        var arrResources = currentAssembly.GetManifestResourceNames();
        foreach (var resourceName in arrResources)
        {
            if (resourceName.ToUpper().EndsWith(embeddedFileName.ToUpper()))
            {
                using (var resourceToSave = currentAssembly.GetManifestResourceStream(resourceName))
                {
                    using (var output = File.OpenWrite(destinationPath))
                        resourceToSave.CopyTo(output);
                    resourceToSave.Close();
                }
            }
        }
    }
  1. Add File to VS Project
  2. Mark as "Embedded Resource" -> File properties
  3. Use name to resolve: [Assembly Name].[Name of embedded resource] like "MyFunkyNTServcice.SelfDelete.bat"

Your code has resource bug (file handle not freed!), please correct to:

public static void extractResource(String embeddedFileName, String destinationPath)
    {
        var currentAssembly = Assembly.GetExecutingAssembly();
        var arrResources = currentAssembly.GetManifestResourceNames();
        foreach (var resourceName in arrResources)
        {
            if (resourceName.ToUpper().EndsWith(embeddedFileName.ToUpper()))
            {
                using (var resourceToSave = currentAssembly.GetManifestResourceStream(resourceName))
                {
                    using (var output = File.OpenWrite(destinationPath))
                        resourceToSave.CopyTo(output);
                    resourceToSave.Close();
                }
            }
        }
    }
等风来 2024-07-25 07:55:57

如果需要,将某些内容提取为字符串:

public static string ExtractResourceAsString(String embeddedFileName)
    {
        var currentAssembly = Assembly.GetExecutingAssembly();
        var arrResources = currentAssembly.GetManifestResourceNames();
        foreach (var resourceName in arrResources)
        {
            if (resourceName.ToUpper().EndsWith(embeddedFileName.ToUpper()))
            {
                using (var resourceToSave = currentAssembly.GetManifestResourceStream(resourceName))
                {
                    using (var output = new MemoryStream())
                    {
                        resourceToSave.CopyTo(output);
                        return Encoding.ASCII.GetString(output.ToArray());
                    }
                }
            }
        }

        return string.Empty;
    }

Extract something as string, if needed:

public static string ExtractResourceAsString(String embeddedFileName)
    {
        var currentAssembly = Assembly.GetExecutingAssembly();
        var arrResources = currentAssembly.GetManifestResourceNames();
        foreach (var resourceName in arrResources)
        {
            if (resourceName.ToUpper().EndsWith(embeddedFileName.ToUpper()))
            {
                using (var resourceToSave = currentAssembly.GetManifestResourceStream(resourceName))
                {
                    using (var output = new MemoryStream())
                    {
                        resourceToSave.CopyTo(output);
                        return Encoding.ASCII.GetString(output.ToArray());
                    }
                }
            }
        }

        return string.Empty;
    }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文