views:

45

answers:

2

I'm working on a WP7 app. The app will have a couple of XML files. Some are read-write, a couple are read-only. What are my options here? IsolatedStorage? Embedding as resources?

I'll also need to know...

  1. How would I load the XML into XElements from either?
  2. How would I save from an XElement into either?
+2  A: 

For write access you will need to use IsolatedStorage. You can check if the file exists and load it from IsolatedStorage otherwise load it from a resource. For read-only access you can just load it from a resource. Add the xml files to your project check Build Action is Content.

XDocument doc = LoadFromIsolatedStorage(name);
if (doc == null)
{
    doc = LoadFromResource(name);
}

////////////////////////////

public static XDocument LoadFromResource(string name)
{
    var streamInfo = Application.GetResourceStream(new Uri(name, UriKind.Relative));
    using(var s = streamInfo.Stream)
        return XDocument.Load(s);

}

public static XDocument LoadFromIsolatedStorage(string name)
{
    using (var store = IsolatedStorageFile.GetUserStoreForApplication())
    {
        if (store.FileExists(name))
        {
            using(var stream = store.OpenFile(name,FileMode.Open))
                return XDocument.Load(stream);
        }
        else
            return null;
    }
}

public static void SaveToIsolatedStorage(XDocument doc, string name)
{
    using (var store = IsolatedStorageFile.GetUserStoreForApplication())
    {
        var dir = System.IO.Path.GetDirectoryName(name);
        if (!store.DirectoryExists(dir))
            store.CreateDirectory(dir);
        using (var file = store.OpenFile(name, FileMode.OpenOrCreate))
            doc.Save(file);
    }
}
Kris
Awesome. Thanks.
Shlomo
A: 

Just for thought, do you wanna run the "xap" as an "exe" with all documents included? If so you can use the tool Desklighter (http://blendables.com/labs/desklighter/).

Krish Silva
This won't work. It's for Windows Phone.
Shlomo