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?
Open Solution Explorer add files you want to embed. Right click on the files then click on Properties . In Properties window and change Build Action to Embedded Resource . After that you should write the embedded resources to file in order to be able to run it.
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).
public void WriteResourceToFile(string resourceName, string fileName) { using(var resource = Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceName)) { using(var file = new FileStream(fileName, FileMode.Create, FileAccess.Write)) { resource.CopyTo(file); } } }
I have found that the easiest way to do this is to use Properties.Resources
and File
. Here is the code I use (requires using System.IO
)...
For Binary files: File.WriteAllBytes(fileName, Properties.Resources.file);
For Text files: File.WriteAllText(fileName, Properties.Resources.file);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With