Come pacchetto gestito C # DLL con un C # un'applicazione gestita senza lasciare file dietro?

StackOverflow https://stackoverflow.com/questions/2452114

  •  20-09-2019
  •  | 
  •  

Domanda

Ho letto attraverso le altre due thread che estraggono la DLL dall'applicazione in fase di esecuzione. Uno di questi metodi utilizzati nella directory temporanea di Windows corrente per salvare la dll in, ma era una DLL non gestita e doveva essere importato in fase di esecuzione con DllImport. Supponendo che il mio DLL gestita esportato nella directory temporanea, come posso collegare correttamente che assembly gestito per il mio attuale progetto # MSVC?

È stato utile?

Soluzione

Non avete bisogno di salvare in una directory temp a tutti. Basta mettere la DLL gestita come un 'Risorsa incorporata' nel progetto. Poi associare l'evento AppDomain.AssemblyResolve e nel caso, caricare la risorsa come flusso di byte e caricare l'assembly dal flusso e restituirlo.

Codice di esempio:

// Windows Forms:
// C#: The static contructor of the 'Program' class in Program.cs
// VB.Net: 'MyApplication' class in ApplicationEvents.vb (Project Settings-->Application Tab-->View Application Events)
// WPF:
// The 'App' class in WPF applications (app.xaml.cs/vb)

static Program() // Or MyApplication or App as mentioned above
{
    AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(CurrentDomain_AssemblyResolve);
}

static Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
{
    if (args.Name.Contains("Mydll"))
    {
        // Looking for the Mydll.dll assembly, load it from our own embedded resource
        foreach (string res in Assembly.GetExecutingAssembly().GetManifestResourceNames())
        {
            if(res.EndsWith("Mydll.dll"))
            {
                Stream s = Assembly.GetExecutingAssembly().GetManifestResourceStream(res);
                byte[] buff = new byte[s.Length];
                s.Read(buff, 0, buff.Length);
                return Assembly.Load(buff);
            }
        }
    }
    return null;
} 
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top