GetManifestResourceStream giving Null Reference exception ( Parameter name: streamSource) - c#

I keep on getting a null reference exception from GetManifestResourceStream, am trying to add Logo image to the Lightswitch ribbon and it is supposed to work just fine....
was referring to LR__ http://social.msdn.microsoft.com/Forums/en-US/lightswitch/thread/2d16c638-f833-4c4c-beec-656912a87b8e/#76fa5382-0135-41ba-967c-02efc3f8c3a2
System.Windows.Media.Imaging.BitmapImage image = new System.Windows.Media.Imaging.BitmapImage();
image.SetSource(Assembly.GetExecutingAssembly().GetManifestResourceStream(
Application.Current.Details.Name + ".Resources.logo.jpg"));
Image myImage = new Image()
{
Source = image,
Stretch = System.Windows.Media.Stretch.Uniform,
HorizontalAlignment = HorizontalAlignment.Left,
Margin = new Thickness(2, 2, 2, 14),
Cursor = System.Windows.Input.Cursors.Hand
};
I tried a lot of things but I can't find my where the problem is!!

add your image or file in your project then select your file on the solution explorer window then on the properties window select Build Action then set value "Embedded Resource" to Build Action properties
just this

Does Logo.jpg have it's build action set to "Embedded Resource"?
Edit:
Here the C# translation of my GetResourceUri (note, it needs a Resource, not an Embedded Resource):
public Uri GetResourceUri(this Assembly asm, string resourceName)
{
Uri result = null;
var assemblyName = new AssemblyName(asm.FullName).Name;
result = new Uri(string.Format("/{0};component/{1}", assemblyName, resourceName), UriKind.Relative);
return result;
}
The same "technique" should work in C#.
I also have a custom shell extension (that uses LR's technique to add images to both the ribbon & the navigation menu). I'm just finishing a few things (writing the "documentation" is taking some time) & then I'll release it on the Visual Studio Gallery for the community to use (it's called Luminous Classic Shell).
The extension allows you to have the images without needing to write code.

You can use a tool such as Reflector to see the full names of the resources in the Assembly.

I had this null return problem & I was tearing my hair out because this using image files as embedded resources is one of my standard tricks.
I eventually found the reason was that I'd been sent files from a graphic designer who uses an Apple & they didn't work. I fiddled with permissions; used a Paint program to save them in a different format but nothing worked.
In the end I created a completely new file in Paint, then copied & pasted the pixels from the original image. It then worked.
Just for the record, does anyone know why this happened? It must be in the header blocks somehow.

Related

How can I include an image as a Resource in my project?

I want to add an image as a resource in my project so that I can reference it for programmatically inserting into a range in a spreadsheet.
I added the image by right-clicking the project and selecting Add > Existing Item...
I hoped that the image (.png file) would then be available using this code:
var logoRange = _xlSheet.Range[
_xlSheet.Cells[1, LOGO_FIRST_COLUMN],
_xlSheet.Cells[5, LOGO_LAST_COLUMN]];
//System.Drawing.Bitmap logo =
//ReportRunner.Properties.Resources.pa_logo_notap.png;
System.Drawing.Image logo =
ReportRunner.Properties.Resources.pa_logo_notap.png;
_xlSheet.Paste(logoRange, logo);
...but using either Bitmap or Image, I get, "'ReportRunner.Properties.Resources' does not contain a definition for 'pa_logo_notap'"
This seemed like sensible code based on what I read here, but it seems that the image has to be explicitly marked as a resource for this to work. How do I accomplish that?
UPDATE
I tried this:
System.Drawing.Image logo = (System.Drawing.Image)ReportRunner.Properties.Resources.ResourceManager.GetObject("pa_logo_notag.png");
_xlSheet.Paste(logoRange, logo);
...but not only did I get a confirmation msg about the item being pasted not being the same size and shape as the place where it was being inserted, and did I really want to do that, it also inserted some seemingly unrelated text ("avgOrderAmountCell.Style") instead of the image.
UPDATE 2
Okay, I tried this:
Assembly myAssembly = Assembly.GetExecutingAssembly();
System.Drawing.Image logo = (System.Drawing.Image)myAssembly.GetName().Name + ".pa_logo_notap.png";
Clipboard.SetDataObject(logo, true);
_xlSheet.Paste(logoRange, logo);
...but get, "Cannot convert type 'string' to 'System.Drawing.Image' on the second line of that code.
UPDATE 3
This works:
private System.Drawing.Image _logo;
. . .
_logo = logo; // logo (the image) is passed in an overloaded constructor
. . .
var logoRange = _xlSheet.Range[
_xlSheet.Cells[1, LOGO_FIRST_COLUMN], _xlSheet.Cells[6,
LOGO_LAST_COLUMN]];
Clipboard.SetDataObject(_logo, true);
_xlSheet.Paste(logoRange, _logo);
...but I'm not crazy about it, because I'm using an image that is on a form, and passing the image to this class's constructor. Passing images around seems kind of goofy when it should be possible to store the image as a resource and just load the resource. I still haven't gotten that methodology to work, though...
UPDATE 4
I reckon I'll just stick with what I've got (in Update 3), kludgy as it is, because this:
Assembly myAssembly = Assembly.GetExecutingAssembly();
Stream myStream =
myAssembly.GetManifestResourceStream(myAssembly.GetName().Name +
"pa_logo_notap.png");
Bitmap bmp = new Bitmap(myStream);
Clipboard.SetDataObject(bmp, true);
_xlSheet.Paste(logoRange, bmp);
...fails with, "Value of 'null' is not valid for 'stream'"
You have change the build action of the image to be embedded resource.
Then you can reference by doing:
UPDATED
Assembly myAssembly = Assembly.GetExecutingAssembly();
Stream myStream = myAssembly.GetManifestResourceStream( myAssembly.GetName().Name + ".images.pa_logo_notap.png");
Bitmap bmp = new Bitmap(myStream);
My method is to open Resources.resx under Properties. You'll see all your resources laid out on screen.
Click on the downarrow next to 'Add Resource' and you'll see the option Add Existing File. Choose your image name.

c# WPF URI syntax

I am just learning c# and have been struggling to work with URIs in WPF. I've googled around a fair bit but not having much luck.
Essentially I'm trying to have a BitmapImage object stored as a property in a Car object. I then want to display the BitmapImage in an Image control on a WPF form.
The app is a simple app (it's for a Uni assignment), so no database, etc.
I have two methods of doing this. The first is that I'm preloading Car data from a text file, including the filename of the JPG I want to load. I have included the JPG in a directory called Files which is off the main directory where my source code and class files are. I have set the JPG file to 'Content' and 'Always copy'. When I run a Debug, it copies the Files directory and the JPG to the debug\bin directory.
My code creates a BitmapImage by referring to the JPG using a URI as follows;
BitmapImage myImage = new BitmapImage (new Uri("Files/" + Car.Imagefilename, UriKind.Relative);
Car.Image = myImage;
ImageControl.Source = myImage;
If I step through this code in the debugger, it sometimes works and displays the image, but most of the time it doesn't.
My second method is when a user creates a new Car. This method always works. In this one, I use a file dialog box (dlg) to select the image and use an absolute path.
BitmapImage myImage = new BitmapImage (new Uri(dlg.Filename, UriKind.Absolute);
Car.Image = myImage;
ImageControl.Source = myImage;
So....I can't work out why the first method doesn't work. I think it's got something to do with the relative reference, but I can't work out how to syntax that properly to work. I've tried using "pack:,,,", I've tried adding "component", I've tried an '#' before the "pack". I can't seem to find something that explains this simply.
Apologies if this is straight forward but it's doing my head in! Appreciate any pointers.
If the image files are located in a "Files" folder of your Visual Studio project, you should set their Build Action to Resource (and Copy to Output Directory to Do not copy), and load them by a Resource File Pack URI:
var image = new BitmapImage(new Uri("pack://application:,,,/Files/" + Car.Imagefilename));
Car.Image = image;
ImageControl.Source = image;
There is no need to copy the files anywhere. Images are loaded directly from the assembly.
First try to load the image file using its absolute path. For example if the images are stored in c:\projects\yourproject\files, then try using something like
BitmapImage myImage = new BitmapImage (new Uri("c:/projects/yourproject/files/carname.jpg", UriKind.Absolute);
If it works, what you are facing is an path calculation issue.
At this point you may either calculate the Absolute with reference to your executable using AppDomain.CurrentDomain.BaseDirectory at runtime or use App.Config to store the path and reference it from there.
Cheers

How to get all files list from a relative URI in XAML application?

How to get all files from a folder in XAML application using relative path?
I am playing with a Kinect application built in WPF. All images used in the application are in
[project dir]\Images\ and all backgrounds are in
[project dir]\Images\Backgrounds\.
I want to get list of all the images from Backgrounds directory using relative path. I have tried
DirectoryInfo(#"\Images\Backgrounds\").GetFiles();
but it says that Backgrounds directory must exist in [full path+project dir]\debug\bin\
Selecting each image manually works fine
Uri uri = new Uri(#"Images\Backgrounds\Background1.png", UriKind.Relative);
ImageSource imgsource = new BitmapImage(uri);
this.Backdrop.Source = imgsource;
It works for a single file because you specify URI to resource embedded in the assembly and not some folder on your drive, whilst GetFiles() will work only on a specific physical folder. So either you need to copy all your images instead of embedding them or use the code below and resourceNames should give you names of all resources that you can reference by URI in your project:
List<string> resourceNames = new List<string>();
var assembly = Assembly.GetExecutingAssembly();
var rm = new ResourceManager(assembly.GetName().Name + ".g", assembly);
try
{
var list = rm.GetResourceSet(CultureInfo.CurrentCulture, true, true);
foreach (DictionaryEntry item in list)
resourceNames.Add((string)item.Key);
}
finally
{
rm.ReleaseAllResources();
}
if you need then at this point each item.Value contains UnmanagedMemoryStream for each resource.
I would reply to your post instead of posting a solution, but I'm new to this site and dont have that privledge yet.... Hey! Just trying to help.
Anyway, I've had a problem similar to this before concerning DirectoryInfo. Can't remember exactly how I solved it, but I remember the backslashes being tricky. Have you checked out the MSDN site? It seems like it can't find your directory so its looking for it in debug by default. MSDN says the format should be "MyDir\MySubdir" in C#.

How to set relative path to Images directory inside C# project?

I am working on C# project i need to get the images from Images directory using relative path. I have tried
var path = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location) + #"\Images\logo.png";
var logoImage = new LinkedResource(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location)+#"\Images\logo.png")
But no luck with these...
I have made the images to be copied to output directory when the program is running but it doesn't pickup those images.
If you are using LinkedResource() in C# it is most likely not to pickup your relative URI or the file location.
You can use some extra piece of code
var outPutDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().CodeBase);
var logoimage = Path.Combine(outPutDirectory, "Images\\logo.png");
string relLogo = new Uri(logoimage).LocalPath;
var logoImage = new LinkedResource(relLogo)
Now it will pickup your relative path, convert this to absolute path in memory and it will help you get the images.
First, add those image file to your project (create an Image folder is a good idea)
Second, select the image in your solution manager, and view the property window.
And then, change the "copy to output folder" to "always" or "copy when update".
PS. My IDE is Trad. Chinese so I can not ensure the correct keywords in your language.
I would make sure that the Images directory is in the output folder.
I usually use Assembly.GetExecutingAssembly().Location to get the location of my dll.
However, for images, I usually use the Resources page/collection in the project's Properties page. Here is more information about it. Putting the image in the project's Resource would automatically give you an easy way to access it.
For more information about GetExecutingAssembly: MSDN Page
if u want to display images in your folder using your application use an array and put all pictures in ur folder into array. then you can go forward and backward.
string[] _PicList = null;
int current = 0;
_PicList = System.IO.Directory.GetFiles("C:\\Documents and Settings\\Hasanka\\
Desktop\\deaktop21052012\\UPEKA","*.jpg");
// "*.jpg" will select all
//pictures in your folder
String str= _PicList[current];
DisplayPicture(str);
private void DisplayPicture(string str)
{
//throw new NotImplementedException();
BitmapImage bi = new BitmapImage(new Uri(str));
imagePicutre.Source = bi; // im using Image in WPF
//if u r using windows form application it must be a PictureBox i think.
label1.Content = str;
}

Application.GetResourceStream called on a Content Resource still return null

Here is the task-related part of the VS2010 project (Windows Phone) structure:
The code is being executed from DummyMediaLibProvider.cs:
public class DummyMediaLibProvider: IMediaLibProvider
{
...
StreamResourceInfo albumArtPlaceholder =
Application.GetResourceStream(
new Uri("../Images/artwork.placeholder.png", UriKind.Relative));
artwork.placeholder.png Build Action is set to Content.
Still, whenever I run the code, Application.GetResourceStream returns null.
What may be the reason for the resource not being read to memory?
I have attempted to delete obj directory of the project, did Clean and Rebuild, but so far nothing helped.
Update:
If I apply Build Action: Resource to artwork.placeholder.png, I can get the resource stream ok though.
P.S. This is not the duplicate of Application.GetContentStream returns null for content Uri since the last had the extension (particurarly .xml) related problem.
The path supplied Application.GetResourceStream isn't relative to the position of the class, but relative to the application package.
StreamResourceInfo albumArtPlaceholder =
Application.GetResourceStream(
new Uri("Images/artwork.placeholder.png", UriKind.Relative));
Would be the correct path. You can also try with a full pack URI. (see MSDN)
And finally, Resource would be the correct Build Action for this.

Categories