【问题标题】:C# copy embedded DLL to User FolderC# 将嵌入的 DLL 复制到用户文件夹
【发布时间】:2023-03-09 04:17:01
【问题描述】:

我有一个需要将嵌入式 DLL 文件复制到用户目录的 C# WinForms 应用程序。 我无法让我的应用程序识别嵌入式 DLL 文件。有人可以帮忙吗?

系统不断抛出异常参数“eContactAutoCAD.dll 不存在”——显然变量为空。

为了让系统识别嵌入文件,我需要进行哪些更改?

namespace eContact_AutoCAD_Installer
{
  public partial class Form1 : Form
  {
    public Form1()
    {
        InitializeComponent();
    }        
    
    const string dllFolder = @"C:\eContact\";
    const string dllFile = @"C:\eContact\eContactAutoCAD.dll";
    const string EMBED_DLLFILE = "eContact_AutoCAD_Installer.Files.eContactAutoCAD.dll";

   /*
     ---
   */
    
    //Copy DLL to User's "C:/eContact/" folder
    private static void copyDLL()
    {
        if (!Directory.Exists(dllFolder))
        {
            Directory.CreateDirectory(dllFolder);
        }
        try
        {


            using (Stream resource = Assembly.GetExecutingAssembly().GetManifestResourceStream(EMBED_DLLFILE))
            {
                if (resource == null)
                {
                    throw new ArgumentException("eContactAutoCAD.dll does not exist");
                }
                using (Stream output = File.OpenWrite(dllFile))
                {
                    resource.CopyTo(output);
                }
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message, "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
        }
    }

   /*
     ---
   */
  }
}

【问题讨论】:

    标签: c# embedded-resource


    【解决方案1】:

    此示例代码应涵盖主要问题。

    添加文件时,将其设置为 Embedded Resource,以便文件包含在最终的 exe 中:

    访问资源时,请包含包含该文件的命名空间和文件夹。还可以使用 MemoryStream 访问文件,因为它是二进制数据。

    private int copyDLL()
    {
        var resourceName = "WinFormsApp2.Files.SomeFile.dll";   // resource starts with namespace, then folder name
        MemoryStream ms = new MemoryStream();   // buffer for file bytes
        using (Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceName))  // open resource
        {
            stream.CopyTo(ms);   // copy to buffer
            byte[] bb = ms.ToArray();   // need array to save
            File.WriteAllBytes(@"C:\tmp\SomeFile2.dll", bb);   // save byte array to file
            return bb.Length;  // return file size
        }
    }
    

    【讨论】:

    • 谢谢@Mike67。这很有帮助
    猜你喜欢
    • 2013-07-12
    • 1970-01-01
    • 2017-12-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-10
    相关资源
    最近更新 更多