首页 > 解决方案 > 下载 Execute in Memory Depended EXE C#

问题描述

我想问什么是最好的方法来下载一个 exe 文件,它由 2 个 dll 文件依赖,以便在不接触磁盘的情况下运行!

例如我的下载代码是:

private static void checkDlls()
{
    string path = Environment.GetEnvironmentVariable("Temp");
    string[] dlls = new string[3]
    {
        "DLL Link 1",
        "DLL Link 2",
        "Executalbe File Link"
    };

    foreach (string dll in dlls)
    {
        if (!File.Exists(path + "\\" + dll))
        {
            try
            {
                System.Net.WebClient client = new System.Net.WebClient();
                client.DownloadFile(dll, path+"\\"+dll);
                Process.Start(path + "\\Build.exe");
            }
            catch (System.Net.WebException)
            {
                Console.WriteLine("Not connected to internet!");
                Environment.Exit(3);
            }

        }
    }
}

提前感谢您的回答。

PS:我知道内存中的运行代码丢失了,但这就是我要问的,它还没有实现。

我想在内存中运行的文件是一个 C# exe,它需要 2 个 dll 文件才能运行我想要类似于https://docs.microsoft.com/en-us/dotnet/api/system.net.webclient的东西.downloadstring?view=netcore-3.1但对于我的可执行文件。另外,我想知道这将如何影响进程,因为 dll 是非托管的,无法合并到项目中。

标签: c#memorywebrequestpayload

解决方案


经过搜索和搜索......我找到了这个:)

using System.Reflection;
using System.Threading;

namespace MemoryAppLoader
{
    public static class MemoryUtils
    {
        public static Thread RunFromMemory(byte[] bytes)
        {
            var thread = new Thread(new ThreadStart(() =>
            {
                var assembly = Assembly.Load(bytes);
                MethodInfo method = assembly.EntryPoint;
                if (method != null)
                {
                    method.Invoke(null, null);
                }
            }));

            thread.SetApartmentState(ApartmentState.STA);
            thread.Start();

            return thread;
        }
    }
}

DLL 您必须使用启动器将所有 DLL 复制到目录中,以便正在运行的进程可以访问它们。如果您想将应用程序放在一个文件中,您可以始终将所有应用程序打包在一起并从启动器中解压缩。

也可以使用嵌入式库来准备应用程序。

资料来源:https ://wojciechkulik.pl/csharp/run-an-application-from-memory


推荐阅读