I'm trying to compile the code below using CSharpCodeProvider. The file is successfully compiled, but when I click on the generated EXE file, I get an error (Windows is searching for a solution to this problem) and nothing happens.
When I compile the code below using CSharpCodeProvider, I've added the MySql.Data.dll
as an embedded resource file using this line of code:
if (provider.Supports(GeneratorSupport.Resources))
cp.EmbeddedResources.Add("MySql.Data.dll");
The file is successfully embedded (because I noticed the file size increased).
In the code below, I try to extract the embedded DLL file and save it to System32, but the code below doesn't work for some reason.
namespace ConsoleApplication1
{
class Program
{
public static void ExtractSaveResource(String filename, String location)
{
//Assembly assembly = Assembly.GetExecutingAssembly();
Assembly a = .Assembly.GetExecutingAssembly();
//Stream stream = assembly.GetManifestResourceStream("Installer.Properties.mydll.dll"); // or whatever
//string my_namespace = a.GetName().Name.ToString();
Stream resFilestream = a.GetManifestResourceStream(filename);
if (resFilestream != null)
{
BinaryReader br = new BinaryReader(resFilestream);
FileStream fs = new FileStream(location, FileMode.Create); // Say
BinaryWriter bw = new BinaryWriter(fs);
byte[] ba = new byte[resFilestream.Length];
resFilestream.Read(ba, 0, ba.Length);
bw.Write(ba);
br.Close();
bw.Close();
resFilestream.Close();
}
// this.Close();
}
static void Main(string[] args)
{
try
{
string systemDir = Environment.SystemDirectory;
ExtractSaveResource("MySql.Data.dll", systemDir);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Console.ReadKey();
}
}
}
}
How can I extract the DLL file that is embedded as a resource and save it to System32?
Or using an extension method...
I've been using this (tested) method:
OutputDir: Location where you want to copy the resource
ResourceLocation: Namespace (+ dirnames)
Files: List of files within the resourcelocation, you want to copy.
I'd suggest doing it easier. I assume that the resource exists and the file is writable (this might be an issue if we're speaking about system directories).
Try reading your target assembly into a
MemoryStream
and then saving to aFileStream
like this (please bear in mind that this code isn't tested):This works perfectly!
Example of usage:
If this still doesn't help, try this video out: https://www.youtube.com/watch?v=_61pLVH2qPk
I have found that the easiest way to do this is to use
Properties.Resources
andFile
. Here is the code I use...For Binary files:
File.WriteAllBytes(fileName, Properties.Resources.file);
For Text files:
File.WriteAllText(fileName, Properties.Resources.file);