在我的应用程序中,我使用CodeDom.Compiler从source.cs文件编译另一个程序,并在编译时使用以下命令嵌入一些资源(exe和dll文件):
// .... rest of code
if (provider.Supports(GeneratorSupport.Resources))
{
cp.EmbeddedResources.Add("MyFile.exe");
}
if (provider.Supports(GeneratorSupport.Resources))
{
cp.EmbeddedResources.Add("New.dll");
}
// ....rest of code
在编译文件中,我需要将嵌入资源作为字节数组读取。现在我通过使用下面的函数和使用
将资源提取到磁盘来实现这一点File.ReadAllBytes("extractedfile.exe");
File.ReadAllBytes("extracteddll.dll");
我使用此函数将两个文件解压缩到磁盘后执行此操作:
public static void ExtractSaveResource(String filename, String location)
{
// Assembly assembly = Assembly.GetExecutingAssembly();
System.Reflection.Assembly a = System.Reflection.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();
}
我怎样才能做同样的事情(将嵌入资源作为字节数组获取)但不向硬盘写任何内容?
答案 0 :(得分:28)
您实际上已经将流读取到字节数组,为什么不停在那里?
public static byte[] ExtractResource(String filename)
{
System.Reflection.Assembly a = System.Reflection.Assembly.GetExecutingAssembly();
using (Stream resFilestream = a.GetManifestResourceStream(filename))
{
if (resFilestream == null) return null;
byte[] ba = new byte[resFilestream.Length];
resFilestream.Read(ba, 0, ba.Length);
return ba;
}
}
编辑:查看评论以获得更好的阅读模式。
答案 1 :(得分:2)
使用MemoryStream
的简单替代方法:
var ms = new MemoryStream();
await resFilestream.CopyToAsync(ms);
var bytes = ms.ToArray();
答案 2 :(得分:0)
Keep in mind that Embedded resource filename = Assemblyname.fileName
`string fileName = "test.pdf";
System.Reflection.Assembly a =
System.Reflection.Assembly.GetExecutingAssembly();
string fileName = a.GetName().Name + "." +
"test.pdf";
using (Stream resFilestream =
a.GetManifestResourceStream(fileName))
{
if (resFilestream == null) return null;
byte[] ba = new
byte[resFilestream.Length];
resFilestream.Read(ba, 0, ba.Length);
var byteArray= ba;
}`
答案 3 :(得分:0)
File.WriteAllBytes(@"C:\Users\admin\Desktop\MyFile.exe", Resources.BinFile); // binary file
File.WriteAllText(@"C:\Users\admin\Desktop\text.txt", Resources.TextFile); // text file