TotalJargon
TotalJargon

Reputation: 147

WP7 - Error 'XmlException was unhandled' despite checking if the file exists

I'm attempting to read from an XML document in WP7 and have run into a weird error that I simply just don't get, when I run my program from the first time after restarting the WP7 emulator but if I run it in debug without closing the emulator it gives me the runtime error: 'XmlException was unhandled Cannot find file 'appdata.xml' in the application xap package.' which is strange because I check to see if the file exists first:

using (var store = IsolatedStorageFile.GetUserStoreForApplication())
{
    if (store.FileExists("appdata.xml"))
    {
        XDocument loadedData = XDocument.Load("appdata.xml"); // <-- runtime error
        //code for parsing xml to variables
    }
}

It enters the if statement so the file should exist but XDocument doesn't like it for some reason, anyone have any ideas?

For further reference here is how I am saving my data when I tap a button in an app, also the error does not occur if this function isn't called:

private void SaveData()
{
    rulesData = new AppData(StartCashRule.Text, LandGoRule.Text, FreeParkingRule.Text, FullCircuitRule.Text, AuctionRule.Text);

    using (var store = IsolatedStorageFile.GetUserStoreForApplication())
    {
        IsolatedStorageFileStream ifStream = new IsolatedStorageFileStream("appdata.xml", FileMode.OpenOrCreate, store);

        using (XmlWriter writer = XmlWriter.Create(ifStream))
        {
            writer.WriteStartDocument();
            writer.WriteStartElement("myData");

            writer.WriteElementString("Starting_Cash", rulesData.myStartingCash);
            writer.WriteElementString("Land_on_Go_Data", rulesData.myLandOnGo);
            writer.WriteElementString("Free_Parking_Data", rulesData.myFreeParking);
            writer.WriteElementString("Full_Circuit_Data", rulesData.myFullCircuit);
            writer.WriteElementString("Auction_Data", rulesData.myAuction);

            writer.WriteEndElement();
            writer.WriteEndDocument();
        }

        ifStream.Close();
    }
}

Thanks - Ryan

Upvotes: 1

Views: 765

Answers (1)

Steve
Steve

Reputation: 216313

You are passing to XDocument.Load the name "appdata.xml" without any reference to the IsolatedStorage store where the file really exists.

You should write something like this

XDocument loadedData = XDocument.Load(store.OpenFile("appdata.xml", FileMode.Open));

Upvotes: 4

Related Questions