[英]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:
我想做以下事情:
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:添加类型资源:
Resources
tab Resources
选项卡File
as resource type 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.