Tôi đang cố gắng biên dịch mã dưới đây bằng cách sử dụng CSharpCodeProvider. Tệp được biên dịch thành công, nhưng khi tôi nhấp vào tệp EXE đã tạo, tôi gặp lỗi (Windows đang tìm kiếm giải pháp cho vấn đề này) và không có gì xảy ra.Làm cách nào để trích xuất tệp từ tài nguyên được nhúng và lưu tệp đó vào đĩa?
Khi tôi biên dịch mã dưới đây sử dụng CSharpCodeProvider, tôi đã thêm MySql.Data.dll
như một file nguồn nhúng sử dụng dòng mã này:
if (provider.Supports(GeneratorSupport.Resources))
cp.EmbeddedResources.Add("MySql.Data.dll");
Các tập tin được nhúng thành công (vì tôi nhận thấy kích thước tập tin tăng).
Trong mã bên dưới, tôi cố trích xuất tệp DLL được nhúng và lưu tệp đó vào System32, nhưng mã bên dưới không hoạt động vì một số lý do.
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();
}
}
}
}
Làm cách nào để trích xuất tệp DLL được nhúng dưới dạng tài nguyên và lưu tệp vào System32?
Rafik, bạn nên xem lại câu trả lời của Thomas Sapp dưới đây vì nó hoàn toàn tốt hơn câu trả lời bạn chấp nhận. – motoDrizzt