I have an embedded resource named "Test.exe". I want to do the following:
- Read the contents of Tes开发者_StackOverflow中文版t.exe into a byte array.
- Write the contents of Test.exe (now in a byte array) to a new location (C:\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.
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);
}
Once you get the exact name of the embedded resource pass it to the ReadResource
method.
As yet another alternative you could use ildasm.exe and double click on the MANIFEST
which will show you all embedded resources.
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 - select
File
as resource type add your executable file to the resources
now you can reference the file content by
Resources.TestFile
精彩评论