繁体   English   中英

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

[英]c# read byte array from resource

我一直在试图弄清楚如何从我的一个资源文件中读取字节数组,我已经尝试了谷歌上最受欢迎的点击但没有明显的成功。

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

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

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

但是,我想将该文件作为资源存储在我的应用程序中,这样我就不必随程序一起发送额外的文件。

该文件包含我的部分程序使用的加密数据。

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

假设您正在讨论作为程序集中的资源嵌入的文件:

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
}

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

文档

之后,您可以轻松地以字节[]的形式访问您的文件:

var myByteArray = Properties.Resources.MyFile;
byte[] capacity = Properties.Resources.excel;

在此处输入图像描述

混乱: 在此处输入图像描述

在这里我们读取 txt 资源文件。所以它不返回byte[]但它返回string (文件内容)。

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

也许你可以尝试使用StreamResourceInfo。 这是一个Silverlight示例的链接,但如果我没有弄错,您应该能够在任何.NET应用程序中应用相同的原则:

http://msdn.microsoft.com/en-us/library/system.windows.resources.streamresourceinfo(v=VS.95).aspx

问候,
安德斯@Cureos

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM