views:

414

answers:

2

I have a WPF application which saves its data to XML files in a relative-to-code directory called "Data".

I get the relative path to the Data directory with these methods:

protected string ApplicationPath
{
    get { return System.IO.Path.GetDirectoryName(System.Reflection.Assembly
          .GetExecutingAssembly().CodeBase); }
}

protected string ApplicationDataPath
{
    get { return ApplicationPath + @"..\..\..\Data\"; }
}

public string FullXmlDataStorePathAndFileName
{
    get
    {
        return ApplicationDataPath + GetItemTypeIdCode() + ".xml";
    }
}

This works for testing since the Debug or Relates .exe will go back up into the project and access the data.

Problem #1 with this is it doesn't work when saving the XML file, I get a "URI formats are invalid" error, it seems it can't deal with the "......\" part of the path when saving:

xmlDoc.Save(FullXmlDataStorePathAndFileName);

Problem #2 is that when I want to deploy my app (e.g. make it available for download so someone unzips and double-clicks on the .exe), then the .xml files need to be in the same directory as the .exe or one lower in a Data directory so that each instance of the application can read and write to its own XML files.

What is the best solution for this? Requirements are:

  • XML files should be locally under the project and transparent when developing and testing, e.g. edit the XML files in Visual Studio and "Copy to Output Directory" is "Copy if Newer", so while developing, the base data is always refreshed when press F5

  • a straight-forward way of e.g. zipping up the "Release" directory and all of the files (.exe and original XML files) are there and the paths in the .exe point to the XML files upon starting

Has anyone developed a good solution to having a local XML data source in a relative directory like this?

+2  A: 

You could have your xml path in a separate config file?

Or you can use conditionals (#if DEBUG / #endif) to have separate logic for your debug version.

But I would recommend a more appropriate place for such data, something like (system disk)\Users\UserName\AppData\Roaming\AppName(etc). If your app is installed in Program Files, then your app would need additional permissions to save files there. In Vista, this would mean you would have to run your app with raised privileges, even if your account is admin (with UAP enabled).

Groo
+1  A: 

Maybe I misunderstand the question, but if your XML file is set to "Copy to Output Directory - Copy if newer", then you should be able to access it directly in the bin\Debug folder. So your xml file can be referenced in the same folder as the exe when you are debugging and when you deploy.

John Myczek