将supportedRuntime嵌入到exe文件中

13

我需要将只包含supportedRuntime设置的app.config文件嵌入到我的exe文件中。我尝试使用“嵌入资源”构建操作,但现在它无法读取配置文件中的值,因此无法正常工作。这是我的配置文件:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <startup>
      <supportedRuntime version="v2.0.50727"/>
      <supportedRuntime version="v4.0"/>
    </startup>
</configuration>

那么想法是在.Net 4.0上运行我的.Net 2.0 exe。有任何想法吗?

谢谢。


.NET是向后兼容的。如果一台机器安装了4.0,它将运行使用2.0编译的应用程序。您不需要两个标签。 - Andrew
12
谢谢您,安德鲁,但不幸的是那并不是真的。 - Shahab78
试试这个:https://dev59.com/bGYr5IYBdhLWcg3wJ3CU#13915723 - Andrew
6
谢谢Andrew,他说得完全正确,但是我提到我正在尝试找到一种不需要配置文件或将配置文件嵌入exe的方法来完成这个任务。 - Shahab78
1个回答

6
这是不可能的。如果你非常需要没有配置文件的可执行文件,你能做到的最接近的方法是编写一个非托管的加载器来运行CLR。
假设你有一个C#应用程序,如下所示:
using System;

namespace DumpVersion
{
    class Program
    {
        static int EntryPoint(string argument)
        {
            Console.Out.WriteLine(argument);
            Console.Out.WriteLine(Environment.Version);
            Console.In.ReadLine();
            return 0;
        }

        static void Main()
        {
            EntryPoint("Main");
        }
    }
}

您可以创建不受管理的()加载程序,例如:

#include <metahost.h>

#pragma comment(lib, "mscoree.lib")

#import "mscorlib.tlb" raw_interfaces_only \
    high_property_prefixes("_get","_put","_putref") \
    rename("ReportEvent", "InteropServices_ReportEvent")

int wmain(int argc, wchar_t* argv[])
{
    HRESULT hr;
    ICLRMetaHost *pMetaHost = NULL;
    ICLRRuntimeInfo *pRuntimeInfo = NULL;
    ICLRRuntimeHost *pClrRuntimeHost = NULL;

    // build runtime
    // todo: add checks for invalid hr 
    hr = CLRCreateInstance(CLSID_CLRMetaHost, IID_PPV_ARGS(&pMetaHost));
    hr = pMetaHost->GetRuntime(L"v4.0.30319", IID_PPV_ARGS(&pRuntimeInfo));
    if (hr != S_OK) {
        hr = pMetaHost->GetRuntime(L"v2.0.50727", IID_PPV_ARGS(&pRuntimeInfo));
    }
    hr = pRuntimeInfo->GetInterface(CLSID_CLRRuntimeHost,
        IID_PPV_ARGS(&pClrRuntimeHost));

    // start runtime
    hr = pClrRuntimeHost->Start();

    // execute managed assembly
    DWORD pReturnValue;
    hr = pClrRuntimeHost->ExecuteInDefaultAppDomain(
        L"c:\\temp\\TestLoading\\DumpVersion\\bin\\Debug\\DumpVersion.exe",
        L"DumpVersion.Program",
        L"EntryPoint",
        L"hello .net runtime",
        &pReturnValue);

    // free resources
    pMetaHost->Release();
    pRuntimeInfo->Release();
    pClrRuntimeHost->Release();

    return 0;
}

更多信息:https://www.codeproject.com/Articles/607352/Injecting-Net-Assemblies-Into-Unmanaged-Processes


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接