次のコードを使用して実行時に dll ライブラリをロードしようとしています。これにより、メインの実行可能ファイルと共に多くの dll ファイルをユーザーに提供する必要がなくなります。すべての dll ファイルを埋め込みリソースとしてインクルードし、参照部分にもそれらをインクルードし、CopyLocalプロパティを false に設定しました。しかし、ここでの問題は次のとおり
です。 1. すべての dll が Bin\Debug フォルダーにコピーされます
2. FileNotFoundExceptionが発生します。
これらの問題を解決するために多くの検索を行い、最終的にここにいます。ここで同様のコードを取得しましたが、まだ何もできませんでした。この例外を防ぐにはどうすればよいですか...?? Windowsフォームアプリケーション(WPFではない)に対して同じことを行うより良い方法はありますか...??
using System;
using System.Linq;
using System.Windows.Forms;
using System.Diagnostics;
using System.Reflection;
using System.Collections.Generic;
using System.IO;
namespace MyNameSpace
{
static class Program
{
static int cnt;
static IDictionary<string, Assembly> assemblyDictionary;
[STAThread]
static void Main()
{
AppDomain.CurrentDomain.AssemblyResolve += OnResolveAssembly;
if (cnt != 1)
{
cnt = 1;
Assembly executingAssembly = Assembly.GetExecutingAssembly();
string[] resources = executingAssembly.GetManifestResourceNames();
foreach (string resource in resources)
{
if (resource.EndsWith(".dll"))
{
using (Stream stream = executingAssembly.GetManifestResourceStream(resource))
{
if (stream == null)
continue;
byte[] assemblyRawBytes = new byte[stream.Length];
stream.Read(assemblyRawBytes, 0, assemblyRawBytes.Length);
try
{
assemblyDictionary.Add(resource, Assembly.Load(assemblyRawBytes));
}
catch (Exception ex)
{
MessageBox.Show("Failed to load: " + resource + " Exception: " + ex.Message);
}
}
}
}
Program.Main();
}
if (cnt == 1)
{
cnt = 2;
System.Threading.Thread.CurrentThread.Priority = System.Threading.ThreadPriority.Highest;
Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_ThreadException);
Application.ApplicationExit += new EventHandler(Application_ApplicationExit);
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new MainForm());
}
}
private static Assembly OnResolveAssembly(object sender, ResolveEventArgs args)
{
AssemblyName assemblyName = new AssemblyName(args.Name);
string path = assemblyName.Name + ".dll";
if (assemblyDictionary.ContainsKey(path))
{
return assemblyDictionary[path];
}
return null;
}
}
}
コードで不必要に何かを使用している場合は、正しい方法を教えてください...私は、論文を提出するためにWindows フォーム アプリケーション v4.0プロジェクトに取り組んでいる学生です。