using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace RegisterTool
{
    public static class DllLoader
    {
        // 定义一个临时目录来存储提取的 DLL
        private static readonly string TempDirectory = Path.Combine(Path.GetTempPath(), "RegisterTool");

        // 加载嵌入的 DLL
        public static void LoadEmbeddedDll(string dllName)
        {
            // 确保临时目录存在
            if (!Directory.Exists(TempDirectory))
            {
                Directory.CreateDirectory(TempDirectory);
            }

            // 获取嵌入资源的名称
            string resourceName = $"RegisterTool.Libraries.{dllName}";

            // 检查 DLL 是否已经提取到临时目录
            string tempDllPath = Path.Combine(TempDirectory, dllName);
            if (!File.Exists(tempDllPath))
            {
                // 从嵌入资源中提取 DLL
                using (Stream resourceStream = Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceName))
                using (FileStream fileStream = new FileStream(tempDllPath, FileMode.Create, FileAccess.Write))
                {
                    if (resourceStream != null)
                    {
                        resourceStream.CopyTo(fileStream);
                    }
                }
            }

            // 动态加载提取的 DLL
            Assembly.LoadFrom(tempDllPath);
        }
    }
}
