Content or Resource Files?…Another way to load a static XML file to your application…
So as these things usually go, while doing something completely unrelated to the application I recently built, I found another way to load static XML content into your Silverlight/Windows Phone application. Instead of adding a file and setting its Build Action to Resource, as shown in my previous blog post, and accessing the file in code with Application.GetResourceStream, you can also set the Build Action property for the file to Content:
and then load the file contents directly into an XElement simply by calling the Load method and passing the content file name.
XElement myElement = XElement.Load("data.xml");
So after discovering this method of loading the file, my next question was, which is better…Resource or Content files? The answer is, of course, it depends.
Here’s what I found digging around in the docs:
Resource Files
The Resource build action will embed the file in the project assembly. You can use this option with application and library projects, and deploy the assemblies inside or outside the application package. You can ensure the data file will always be available to the application by using the Resource build action.
You should use resource files when:
You don't need to update the resource file's content after it is compiled into an assembly.
You want to simplify application distribution complexity by reducing the number of file dependencies.
Content Files
The Content build action will include the file in the application package without embedding it in the project assembly. Use this option for resource files shared by multiple assemblies in the package. Although they are not compiled into an assembly, assemblies are compiled with metadata that establishes an association with each content file.
You should use content files when your application requires a specific set of application data files that you want to be able to update without recompiling the assembly that consumes them.
I am sure there are other reasons for choosing either Content or Resource…I just haven’t found them yet!
--Cheryl
Comments
Anonymous
May 31, 2011
Resource files make your assembly larger, which makes assembly verification take longer, which makes your app take longer to launch.Anonymous
October 18, 2012
Also embedding files as resource files in the assembly allows to list them at runtime using the GetManifestResourceXXX methods on the Assembly class. This seems to be impossible when put as content files.Anonymous
November 06, 2012
How to access any file if it is used as Build action: content, and used always copy in silverlight application.