February17

Create a file from a resource on WP7

I got an email from someone today asking about how to take a resource from their XAP (which is read only), and put it in a location where they can update the file. 

Initial Data Load

I highly recommend this approach for getting an initial data load for your application.  Give the application a base of files to work with rather than requiring an initial round trip to a server for those files.  It is fine to need to update them almost immediately.  Think about the scenario where the user has no network access (a first run of the app this is really vital).  Does the user get an error that no data is available, or do they get a nice default experience?  Even if you just put in data that says “no data here yet”, that is better than a blank screen to the user.

Create File From Resource

I put this in a utilities class as a static method since it doesn’t really need any state.  One thing to ensure you do is put a using() block around the objects that are disposable.  This ensures they are cleaned up and released as quickly as possible.  I think this is a common reason why people think they need to GC.Collect, they are not cleaning up memory.

public class FileUtilities
{
/// <summary>
/// Given a resource name, create a file in the isolated storage.
/// Resources are read only, but copying them to the isolated store means you can edit them.
/// Useful for including a starter file in your XAP, and then copying it out to storage
/// for editing it at runtime.
/// </summary>
/// <param name="resourceName">The name of the resource</param>
/// <param name="fileName">Optional param for the name of the file, 
///
by default uses the same name as the resource</param> public static void CreateFileFromResource(string resourceName, string fileName = null) { // Find the resource and get the stream // Note the using() block to ensure this gets cleaned up when we are done using (var resourceStream = Application.GetResourceStream(
new Uri(resourceName, UriKind.Relative)).Stream) { // Get the location where we can write files using (var userStorage = IsolatedStorageFile.GetUserStoreForApplication()) { // Use the filename (if given) or the resource name using (var newFile = userStorage.CreateFile(fileName ?? resourceName)) { byte[] byteBuffer = new byte[4096]; int bytesRead = -1; while ((bytesRead = resourceStream.Read(
byteBuffer, 0, byteBuffer.Length)) > 0) { newFile.Write(byteBuffer, 0, bytesRead); } } } } }}

Please forgive the formatting above, trying to make it fit on a smaller size screen.

Comments are closed