c#动态加载dll文件

时间:2021-12-31 20:55:38

1.在写一个记录日志到文件中的类库(生成dll文件copy到一个目录中去,然后在主函数的appconfig中去配置。

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace WriteToTxtLib
{
public class WriteLog
{
public void Write(string logMessage)
{
using (StreamWriter sw = new StreamWriter("e:\\test\\writelog.txt",true))
{
sw.WriteLine(DateTime.Now.ToLongDateString() + logMessage);
}
}
}
}

2.新建一个测试的主函数,其中appconfig进行如下配置

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
<appSettings>
<add key="dllNamespaceName" value="WriteToWordLib"/>
<add key="dllClassName" value="WriteLog"/>
<add key="dllMethodName" value="Write"/>
<add key="dllPath" value="e:\test\WriteToWordLib.dll"/> </appSettings>
</configuration>

3.给主函数添加如下代码

using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Configuration;
using System.Linq;
using System.Management.Instrumentation;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Configuration;
using System.Data;
using System.Drawing;
using System.Text;
using System.IO;
using System.Collections;
using System.Configuration; namespace 我的日志功能函数
{
class Program
{
static void Main(string[] args)
{
WriteLog("主函数开始");
Console.ReadKey();
} private static void WriteLog(string logMessage)
{
/*
* 这是appconfig文件中的指定的内容
<add key="dllNamespaceName" value="WriteToTxtLib"/>
<add key="dllClassName" value="WriteLog"/>
<add key="dllMethodName" value="Write"/>
<add key="dllPath" value="e:\\test\WriteToTxtLib.dll"/>
*/
//获取到命名空间,类名,方法名,dll路径
string dllNamespaceName = System.Configuration.ConfigurationSettings.AppSettings["dllNamespaceName"].ToString();
string dllClassName = System.Configuration.ConfigurationSettings.AppSettings["dllClassName"].ToString();
string dllMethodName = System.Configuration.ConfigurationSettings.AppSettings["dllMethodName"].ToString();
string dllPath = System.Configuration.ConfigurationSettings.AppSettings["dllPath"].ToString(); Assembly asm = Assembly.LoadFile(dllPath);//加载dll
Type classType = asm.GetType(dllNamespaceName + "." + dllClassName);//获取类型
object obj = Activator.CreateInstance(classType);//根据类型创建对象
MethodInfo method = classType.GetMethod(dllMethodName);//找到指定的方法
object o = method.Invoke(obj, new object[] { logMessage });//调用方法
}
}
}