简体   繁体   English

将嵌入式资源读入字节数组时出错(C#)

[英]Error While Reading Embedded Resource into byte array (C#)

I have an embedded resource named "Test.exe".我有一个名为“Test.exe”的嵌入式资源。 I want to do the following:我想做以下事情:

  1. Read the contents of Test.exe into a byte array.将 Test.exe 的内容读入字节数组。
  2. Write the contents of Test.exe (now in a byte array) to a new location (C:\Test.exe).将 Test.exe 的内容(现在在字节数组中)写入新位置 (C:\Test.exe)。

I am using the following code (found on this site) - but the problem is that "s" always returns a null value.我正在使用以下代码(在此站点上找到)-但问题是“s”始终返回 null 值。 I am using the below code as follows: byte[] b = ReadResource("Test.exe");我使用下面的代码如下: byte[] b = ReadResource("Test.exe");

public static byte[] ReadResource(string resourceName)
{
    using (Stream s = Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceName))
    {
        byte[] buffer = new byte[1024];
        using (MemoryStream ms = new MemoryStream())
        {
            while (true)
            {
                int read = s.Read(buffer, 0, buffer.Length);
                if (read <= 0)
                    return ms.ToArray();
                ms.Write(buffer, 0, read);
            }
        }
    }
}  

Hopefully someone can find what I am having trouble seeing.希望有人能找到我看不到的东西。

You need to specify the full name of the resource.您需要指定资源的全名。 So for example if your application is called Foo :例如,如果您的应用程序名为Foo

byte[] b = ReadResource("Foo.Test.exe");

Actually the easiest thing would be to open the assembly with Reflector and look at the exact name of the embedded resource.实际上最简单的方法是使用 Reflector 打开程序集并查看嵌入资源的确切名称。 There might be a namespace in between the name of the application and the name of the resource.应用程序名称和资源名称之间可能存在命名空间。

And if you don't have Reflector (yeah it became a paid product), to find out the names of the embedded resources you could use the following code:如果您没有 Reflector(是的,它已成为付费产品),要找出嵌入资源的名称,您可以使用以下代码:

foreach (var res in Assembly.GetExecutingAssembly().GetManifestResourceNames())
{
    Console.WriteLine(res);
}

Once you get the exact name of the embedded resource pass it to the ReadResource method.获得嵌入资源的确切名称后,将其传递给ReadResource方法。

As yet another alternative you could use ildasm.exe and double click on the MANIFEST which will show you all embedded resources.作为另一种选择,您可以使用ildasm.exe并双击MANIFEST ,它将显示所有嵌入式资源。

You can do this with one line of code if use 'typed' resources.如果使用“类型化”资源,您可以使用一行代码完成此操作。

File.WriteAllBytes("C:\\test1.exe", Resources.TestFile);

To add typed resource:添加类型资源:

  • go to project properties Resources tab go 到项目属性Resources选项卡
  • select File as resource type select File作为资源类型
  • add your executable file to the resources将您的可执行文件添加到资源中

    在此处输入图像描述

  • now you can reference the file content by Resources.TestFile现在您可以通过Resources.TestFile引用文件内容

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

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