13

I added image as file and set type as resource (see screenshot) How do I pull it out as byte array without using resx files, etc?

enter image description here

Cœur
  • 37,241
  • 25
  • 195
  • 267
katit
  • 17,375
  • 35
  • 128
  • 256

3 Answers3

10

Things are even simpler than the item markes as answer!

If you click on the file in resources and view the properties window, you can set the File Type to binary. Then you can access the bytearray in code with a simple

var byteArray = Properties.Resources.FileName;

where FileName is the name of your resource.

Gary Woodfine
  • 387
  • 3
  • 12
  • 4
    Using Visual Studio Express 2010 I wasn't able to change type of a PNG resource, but I renamed the file to .bin prior to adding as a resource and that worked wonderfully! – lapo Dec 03 '13 at 13:37
  • 2
    I cant see any option to change the File Type in Visual Studio 2017 – Lukáš Koten Aug 18 '17 at 07:48
  • Are you sure you're looking in the Properties Window? I just checked in my install of VS2017 and it is definitely there. – Gary Woodfine Sep 05 '17 at 13:36
  • VS 2015: A file that is recognized as an image format is shown on the *Images* view of Resources. The File Type option in Properties seems to be shown only for resources on the *Files* view, however. – nodots Mar 12 '18 at 08:53
  • 1
    There seems to be some confusion as we're talking about two different methods for embedding resources. The OP was talking about setting a file's Build Action to Embedded Resource. You're talking about using a resx file. I don't think the OP knows about that option. – Kyle Delaney May 18 '18 at 16:53
9

The process is described in How to embed and access resources by using Visual C#.

Essentially it requires use of reflection, using the Assembly class.

Stream imageStream = 
            currentAssembly.GetManifestResourceStream("Resources.logo_foot.png");

See How to convert an Stream into a byte[] in C#? for details of how to get a byte[] from a Stream.

Community
  • 1
  • 1
Oded
  • 489,969
  • 99
  • 883
  • 1,009
  • I had to type the entire namespace to get it to work. If you're in doubt which resources you have, call currentAssembly.GetManifestResourceNames() – Paw Baltzersen Apr 09 '13 at 13:28
  • Getting a byte array from a stream seems to be needlessly tricky. I think it's much better to just embed the resource using Resources.resx, and then it will provide access with a `byte[]` instead of a `Stream`. – Kyle Delaney May 18 '18 at 16:32
8

If you dont use the image directly (i.e: from a control if your project is a Windows App) then you could:

1- change the file extension (i.e: *.jpg.data)

2- add the "image" to a resource file RESX

3- access the byte array using: Resources.PathToImages.ResxFileName.ImageName

Note: if you add the image with the extension unchanged the RESX compiler creates a Bitmap property instead of a byte[] property.

Alex Pollan
  • 863
  • 5
  • 13