I have a C# WinForms Application that will need to copy an embedded DLL file to the user's directory. I cannot get my application to recognize the embedded DLL file. Can Someone help?
The system keeps throwing the exception argument "eContactAutoCAD.dll does not exist" - so obviously the variable is null.
What do I need to change in order for the system to recognize the embedded file?
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);
}
}
/*
---
*/
}
}
This example code should cover the main issues.
When adding the file, set it to Embedded Resource so the file is included in the final exe:
When accessing the resource, include the namespace and folder that contains the file. Also use a MemoryStream to access the file since it's binary data.
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
}
}