![](/img/trans.png)
[英]How can I find the names of all shares on a LAN without knowing any machine names using C#?
[英]How can I load all dlls from a folder without knowing their names in c# .net?
以前我使用此調用來加載從Rule類擴展的所有cs文件
var repository = new RuleRepository();
repository.Load(x => x.From(typeof(Rule1).Assembly));
通過如上所示調用Load方法,將所有與Rule1.cs類型相同的類文件(意味着從Rule類擴展的所有文件)加載到存儲庫內存中。 目前,我已決定將所有這些.cs文件(即Rule1.cs)轉換為dll,並掃描包含這些dll的文件夾。 我該如何實現這種行為? 目前我正在做這樣的事情
Assembly assembly1 = Assembly.LoadFile(Server.MapPath("Rule1.dll"));
List<Assembly> asmblyList = new List<Assembly>();
asmblyList.Add(assembly1);
repository.Load(x => x.From(asmblyList));
我想從該文件夾中掃描Rule1.dll類型的所有程序集。 我該怎么辦? 任何幫助都會很棒。
就像在評論中提到的那樣,獲取文件列表並加載它們不是問題,但是只有一種方法可以刪除已加載的程序集,這就是卸載整個AppDomain。 看一下這個例子:
static void Main(string[] args)
{
var path = AssemblyDirectory + @"\external\";
var files = Directory.GetFiles(path); //get all files
var ad = AppDomain.CreateDomain("ProbingDomain"); //create another AppDomain
var tunnel = (AppDomainTunnel)
ad.CreateInstanceAndUnwrap(typeof (AppDomainTunnel).Assembly.FullName,
typeof (AppDomainTunnel).FullName); //create tunnel
var valid = tunnel.GetValidFiles(files); //pass file paths, get valid ones back
foreach (var file in valid)
{
var asm = Assembly.LoadFile(file); //load valid assembly into the main AppDomain
//do something
}
AppDomain.Unload(ad); //unload probing AppDomain
}
private class AppDomainTunnel : MarshalByRefObject
{
public string[] GetValidFiles(string[] files) //this will run in the probing AppDomain
{
var valid = new List<string>();
foreach (var file in files)
{
try
{ //try to load and search for valid types
var asm = Assembly.LoadFile(file);
if (asm.GetTypes().Any(x => x.IsSubclassOf(typeof (Rule1))))
valid.Add(file); //valid assembly found
}
catch (Exception)
{
//ignore unloadable files (non .Net, etc.)
}
}
return valid.ToArray();
}
}
//found here: http://stackoverflow.com/a/283917/4035472
public static string AssemblyDirectory
{
get
{
string codeBase = Assembly.GetExecutingAssembly().CodeBase;
UriBuilder uri = new UriBuilder(codeBase);
string path = Uri.UnescapeDataString(uri.Path);
return Path.GetDirectoryName(path);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.