Search code examples
c#memorywebrequestpayload

Download Execute in Memory Depended EXE C#


I would like to ask what is the best approach in order to download an exe file where it is depended by 2 dll files in order to run without touching the disk!

For example my download code is:

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

        }
    }
}

Thanks in advance for your answers.

PS: i know that the run in memory code is missing but that is what i am asking, it hasn't yet implemented.

The file i want to run in memory is a C# exe where it needs 2 dll files in order to run i want something similar to https://learn.microsoft.com/en-us/dotnet/api/system.net.webclient.downloadstring?view=netcore-3.1 but for my executable file. Plus i want to know how this will affect the process because the dlls are unmanaged and cannot be merged into the project.


Solution

  • After searching and searching.... i found this :)

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

    DLLs You have to copy all of your DLLs to the directory with the launcher, so that the running process can access them. In case you would like to have an application in a single file, you can always pack all together and unpack from the launcher.

    It is also possible to prepare an application with embedded libraries.

    Source: https://wojciechkulik.pl/csharp/run-an-application-from-memory