出现这个错误是因为某些dll无法用LoadFrom加载造成的,一般情况下是环境中缺少这个dll。另外一种情况,当你是遍历bin来反射dll时,如果不影响业务,可以把那些加载不上的dll忽略掉(前提是忽略掉的dll不影响业务)。
下面的try catch的位置,一旦有一个dll加载不上,就直接抛出异常,程序不再往下进行
public static string path = AppDomain.CurrentDomain.BaseDirectory + "\\bin\\";
public Dictionary
{
Dictionary
string tempName = "";
try
{
string[] dicFileName = Directory.GetFileSystemEntries(path);
if (dicFileName != null)
{
List
foreach (string name in dicFileName)
{
if (name.ToLower().IndexOf(".dll") == -1)
{
continue;
}
Assembly assembly = Assembly.LoadFrom(name);
Type[] ts = assembly.GetTypes();
List
foreach (Type t in ts)
{
if (t.GetInterfaces().Length == 0)
{
continue;
}
if ( t.GetInterfaces()[0] != typeof(IActivity))
{
continue;
}
var attrArr = t.GetCustomAttributes(typeof(ActiveAttribute), true);
if (attrArr.Length == 0)
{
continue;
}
ActiveAttribute attr = attrArr[0] as ActiveAttribute;
if (attr != null)
{
tempName = name.Substring(name.LastIndexOf("\\") + 1);
dic.Add(attr.Msg, tempName);
}
}
}
}
}
catch (Exception e)
{
Log4NetHelp.Log.Error(e.Message);
throw new Exception(e.Message);
}
return dic;
}
public static string path = AppDomain.CurrentDomain.BaseDirectory + "\\bin\\";
public Dictionary
{
Dictionary
string tempName = "";
try
{
string[] dicFileName = Directory.GetFileSystemEntries(path);
if (dicFileName != null)
{
List
foreach (string name in dicFileName)
{
if (name.ToLower().IndexOf(".dll") == -1)
{
continue;
}
Assembly assembly = Assembly.LoadFrom(name);
Type[] ts = assembly.GetTypes();
List
foreach (Type t in ts)
{
if (t.GetInterfaces().Length == 0)
{
continue;
}
if ( t.GetInterfaces()[0] != typeof(IActivity))
{
continue;
}
var attrArr = t.GetCustomAttributes(typeof(ActiveAttribute), true);
if (attrArr.Length == 0)
{
continue;
}
ActiveAttribute attr = attrArr[0] as ActiveAttribute;
if (attr != null)
{
tempName = name.Substring(name.LastIndexOf("\\") + 1);
dic.Add(attr.Msg, tempName);
}
}
}
}
}
catch (Exception e)
{
Log4NetHelp.Log.Error(e.Message);
throw new Exception(e.Message);
}
return dic;
}
下面的try catch的位置则可以让程序忽略掉加载不上的dll继续执行
Dictionary
string tempName = "";
string[] dicFileName = Directory.GetFileSystemEntries(path);
if (dicFileName != null)
{
List
foreach (string name in dicFileName)
{
try
{
if (name.ToLower().IndexOf(".dll") == -1)
{
continue;
}
Assembly assembly = Assembly.LoadFrom(name);
Type[] ts = assembly.GetTypes();
List
foreach (Type t in ts)
{
try
{
if (t.GetInterfaces().Length == 0)
{
continue;
}
if (t.GetInterfaces()[0] != typeof(IActivity))
{
continue;
}
var attrArr = t.GetCustomAttributes(typeof(ActiveAttribute), true);
if (attrArr.Length == 0)
{
continue;
}
ActiveAttribute attr = attrArr[0] as ActiveAttribute;
if (attr != null)
{
tempName = name.Substring(name.LastIndexOf("\\") + 1);
dic.Add(attr.Msg, tempName);
}
}
catch (Exception ex)
{
Log4NetHelp.Log.Error(ex.Message);
}
}
}
catch (Exception e)
{
Log4NetHelp.Log.Error(e.Message);
}
}
}
return dic;
}