如何将嵌入的资源读取为字节数组而不将其写入磁盘
本文关键字:数组 字节数 磁盘 资源 读取 字节 | 更新日期: 2023-09-27 18:32:50
在我的应用程序中,我使用 CodeDom.Compiler 从源代码.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();
}
我怎样才能做同样的事情(获取嵌入的资源作为字节数组),但不向硬盘写入任何内容?
您实际上已经将流读取到字节数组,为什么不就此停止呢?
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;
}
}
编辑:查看注释以获取更可取的阅读模式。
使用MemoryStream
的简单替代方案:
var ms = new MemoryStream();
await resFilestream.CopyToAsync(ms);
var bytes = ms.ToArray();
请记住,嵌入的资源文件名 = 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;
}
如果您正在阅读嵌入式资源,这里有一个简单的方法。
string resourcePath = "pack://application:,,,/resource/location/S_2/{0}";
StreamResourceInfo resInfo = Application.GetResourceStream(new Uri(resourcePath));
if (resInfo == null)
{
throw new Exception("Resource not found: " + resourcePath);
}
var ms = new System.IO.MemoryStream();
await resInfo.Stream.CopyToAsync(ms);
byte[] bytes = ms.ToArray();
File.WriteAllBytes(@"C:'Users'admin'Desktop'MyFile.exe", Resources.BinFile); // binary file
File.WriteAllText(@"C:'Users'admin'Desktop'text.txt", Resources.TextFile); // text file