Search code examples
c#filesilverlighturirelative-path

URI Relative Resource in Silverlight


I have a file within my Silverlight project, within a folder.

My project is called Display

Solution Explorer structure:

/Resources
    cube.obj

My code is:

Uri u = new Uri(@"Display;component/Resources/cube.obj", UriKind.Relative);
Stream stream = Application.GetResourceStream(u).Stream;
StreamReader reader = new StreamReader(stream);

cube.obj has the build action set to Content if that's relevant.

I'm getting a NullReferenceException that comes up in the JavaScript and doesn't give me much help in determining the issue.

Any ideas?

Thanks!


Solution

  • Set the file's build action to "Resource", not "Content".

    The NullReferenceException is coming from the Application.GetResourceStream(u).Stream. GetResourceStream returns null because the file isn't available because it's the wrong build action. Accessing Stream on the null reference then fires the exception.

    EDIT: Also make sure that your Uri "Display;" portion is the proper name for your assembly that is housing the obj file.

    Just to clarify. Use Content when you want the file to be placed in the XAP file alongside the various assemblies. You can then access the file without the prefix "Display;component" path. (NOTE: off the top of my head, I don't think I've loaded a "Content" resource in this way with Application.GetResourceStream specifically so I don't know for sure if it will work, but I suspect it would). I also suspect this could cause issues if you have the same file name located in different paths/projects. This method is especially useful if you want to share the same resource/file with multiple projects/assemblies.

    Using Resource will keep the file embedded within the assembly DLL. With this, you need to specify the assembly to look in (hence the "Display;component" prefix). But this is necessary if you're packaging pre-compiled assemblies for use in your Silverlight project or want to manage the files differently.