错误而读嵌入的资源成字节数组(C#)数组、字节、错误、资源

2023-09-06 21:51:19 作者:卟幺¤菽麸

我有一个名为TEST.EXE嵌入的资源。我要做到以下几点:

I have an embedded resource named "Test.exe". I want to do the following:

阅读TEST.EXE的内容复制到一个字节数组中。 写test.exe的(现在处于一个字节数组)的内容复制到新的位置。(C:\ test.exe的)

我使用下面的code(在本网站上找到) - 但问题是,S总是返回一个空值。我现在用的是以下code如下:字节[] B = ReadResource(TEST.EXE);

I am using the following code (found on this site) - but the problem is that "s" always returns a null value. I am using the below code as follows: 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:

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. There might be a namespace in between the name of the application and the name of the resource.

如果你没有反射(是它成为了一个付费产品),要找出您可以使用下面的code嵌入资源的名称:

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:

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

一旦你得到嵌入的资源的确切名称将它传递给 ReadResource 方法。

作为另一种选择,你可以使用程序Ildasm.exe 和双点击清单这会告诉你所有嵌入的资源。

As yet another alternative you could use ildasm.exe and double click on the MANIFEST which will show you all embedded resources.