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

我一直在试图弄清楚如何从我的一个资源文件中读取一个字节数组,我已经尝试过最流行的点击谷歌而没有取得明显的成功。

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

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

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。

文档

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

 var myByteArray = Properties.Resources.MyFile; 

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

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

问候,
安德斯@Cureos

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

 static class EmbeddedResource { ///  /// Extracts an embedded file out of a given assembly. ///  /// The namespace of your assembly. /// The name of the file to extract. /// A stream containing the file data. 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 
 var rm = new ResourceManager("RessourceFile", typeof(ClassXY).Assembly); return Encoding.UTF8.GetBytes(rm.GetString("key"));