下载服务器dll文件并动态加载

1.新加一个类库

namespace ClassLibrary1
{
    public class Class1
    {
        public int Add(int a, int b)
        {
            return a + b;
        }
    }
}
View Code

2.新建一个接口

 [HttpPost]
 [Route("TestStream")]
 public HttpResponseMessage TestStream()
 {
            //获取Debug路径
            string str = Environment.CurrentDirectory;
            var filePath = str + @"ClassLibrary1.dll";
            var result = new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StreamContent(new FileStream(filePath, FileMode.Open))
            };
            result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
           
            return result;
        }
View Code

3.本地调用

 static void Main()
        {
            
            var url = "http://localhost:9921/api/PrintService/TestStream";
            HttpClient client = new HttpClient();
            var response = client.PostAsync(url, new StringContent("", Encoding.UTF8, "application/json")).Result;
            response.EnsureSuccessStatusCode();
            var stream = response.Content.ReadAsStreamAsync().Result;
            
            //获取Debug路径
            string str = Environment.CurrentDirectory;
            var filePath = str + @"ClassLibrary1.dll";
            if (File.Exists(filePath) == false)
            {
                File.Create(filePath);//不存在就创建文件
            }

            StreamToFile(stream, filePath);

            Assembly assembly = Assembly.Load("ClassLibrary1");
            Type type = assembly.GetType("ClassLibrary1.Class1");

            MethodInfo met = type.GetMethod("Add");
            object obj = Activator.CreateInstance(type, null);
            object[] parameter = { 1, 5 };
            var result = met.Invoke(obj, parameter);
            Console.WriteLine("a + b = " + result);

            Console.ReadLine();
        }

        /// <summary>   
        /// 将 Stream 写入文件   
        /// </summary>   
        public static void StreamToFile(Stream stream, string fileName)
        {
            // 把 Stream 转换成 byte[]   
            byte[] bytes = new byte[stream.Length];
            stream.Read(bytes, 0, bytes.Length);
            // 设置当前流的位置为流的开始   
            stream.Seek(0, SeekOrigin.Begin);

            // 把 byte[] 写入文件   
            using (FileStream fs = new FileStream(fileName, FileMode.Open))
            {
                using (BinaryWriter bw =new BinaryWriter(fs))
                {
                    bw.Write(bytes);
                }
            }
        }
View Code
原文地址:https://www.cnblogs.com/xiaoqi742709106/p/6016583.html