C#从资源中读取字节数组

16

我一直在尝试弄清楚如何从我的资源文件之一中读取字节数组,我尝试了谷歌上最受欢迎的方法,但并没有明确的成功。

我有一个存储在程序资源集合中的文件,我想将该文件读取为字节数组

目前我只是使用以下代码从我的程序根目录读取文件:

FileStream fs = new FileStream(Path, FileMode.Open);
BinaryReader br = new BinaryReader(fs);
byte[] bin = br.ReadBytes(Convert.ToInt32(fs.Length));
fs.Close();
br.Close();

然而,我想将这个文件作为应用程序的资源存储,这样我就不必额外携带一个文件来运行程序。

这个文件保存了我的程序使用的加密数据。

任何帮助或指针都将不胜感激!

6个回答

26
假设您正在谈论嵌入在程序集中的资源文件:
var assembly = System.Reflection.Assembly.GetExecutingAssembly();
using (var stream = assembly.GetManifestResourceStream("SomeNamespace.somefile.png"))
{
    byte[] buffer = new byte[stream.Length];
    stream.Read(buffer, 0, buffer.Length);
    // TODO: use the buffer that was read
}

假设你在谈论嵌入在程序集中作为资源的文件 --> 正确的假设 - Raskaroth

22

您可以通过进入项目属性的“资源”选项卡(如果需要,请创建一个),添加资源(现有文件)来向应用程序添加资源。当您添加文件时,可以在其属性中设置它的FileType为Binary。

文档

之后,您可以轻松地将其作为byte[]访问:

var myByteArray = Properties.Resources.MyFile;

谢谢,它对我的当前应用程序没有起作用。但是它确实帮助我处理了一些之前使用资源的其他程序。 - Raskaroth
1
我可以在哪里准确地更改文件类型? - Lukáš Koten
在将文件添加到资源之前,您可以将文件扩展名从txt更改为bin,然后类型将自动变为二进制。或者只需使用文本编辑器打开Resources.resx,并将System.String更改为System.Byte[]。 - Lofrank

1
byte[] capacity = Properties.Resources.excel;

enter image description here

混淆: enter image description here

在这里,我们正在读取txt资源文件。因此,它不会返回byte[],而是返回string(文件内容)。


0

这是我们为此目的使用的一个小类:

static class EmbeddedResource
{
    /// <summary>
    /// Extracts an embedded file out of a given assembly.
    /// </summary>
    /// <param name="assemblyName">The namespace of your assembly.</param>
    /// <param name="fileName">The name of the file to extract.</param>
    /// <returns>A stream containing the file data.</returns>
    public static Stream Open(string assemblyName, string fileName)
    {
        var asm = Assembly.Load(assemblyName);
        var stream = asm.GetManifestResourceStream(assemblyName + "." + fileName);

        if (stream == null)
            throw new ConfigurationErrorsException(String.Format(
                    Strings.MissingResourceErrorFormat, fileName, assemblyName));

        return stream;
    }
}

使用方法非常简单:

using (var stream = EmbeddedResource.Open("Assembly.Name", "ResourceName"))
    // do stuff

0
var rm = new ResourceManager("RessourceFile", typeof(ClassXY).Assembly);
return Encoding.UTF8.GetBytes(rm.GetString("key"));

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接