0

I have a Windows Form project that saves form fields data into a XML file.

When the form is loaded it loads the XML and bind the data to the fields.

Right now the code for getting the XML file is:

DirectoryInfo di = new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory);
string filePath = Path.Combine(di.FullName, "Data.xml");

if (File.Exists(filePath)) {

    XmlSerializer xs = new XmlSerializer(typeof(ConfigurationModel));
    using(FileStream fs = new FileStream(filePath, FileMode.Open)) {
        // This will read the XML from the file and create the new instance
        // of CustomerData
        model = xs.Deserialize(fs) as ConfigurationModel;
    }
}

It works fine in Development but I just packed everything into a Setup file and when I click on the installed icon I get:

enter image description here

So, I guess I have to change the path where the XML is going to be saved.

Any clue?

VAAA
  • 14,531
  • 28
  • 130
  • 253
  • %localAppData%\\ The user should have access to this location. – Sorceri Mar 26 '15 at 19:56
  • %appdata% or %localappdata% – denys-vega Mar 26 '15 at 20:27
  • Excellent summary of where to store anything: http://blogs.msdn.com/b/patricka/archive/2010/03/18/where-should-i-store-my-data-and-configuration-files-if-i-target-multiple-os-versions.aspx – Mitch Mar 26 '15 at 20:38
  • If you're happy to pre-package the values you may also consider embedding the file as a resource in the assembly. http://support.microsoft.com/en-us/kb/319292 – Biscuits Mar 26 '15 at 20:42

1 Answers1

1

You need to either run the program as an administrator (to gain access to the Program Files directory) or save the file elsewhere. A common approach would be to save it in the AppData folder(s). Be aware that if your file is meant to be viewed by users later on, the AppData folders are hidden by default, so you may want to instead save it to the user's specific My Documents folders instead.

GWLlosa
  • 23,995
  • 17
  • 79
  • 116
  • I advise against putting it in _My Documents_. Real estate such as _Desktop_, _My Documents_, _Taskbar_ ...etc are really meant for the user **only**, and not be a dumping ground for individual programs; this is why _Documents & Settings_ was renamed to _My Documents_. If your program has private data that needs to be stored on disk, put it in _AppData_; if it needs to be accessible outside of your program, then add an export function so that users can explicitly do so. At the very least, add an option in your installer to give the user the option of opting out of putting the files there. – Setsu Mar 26 '15 at 20:56
  • I agree with you in general, but without knowing the specific use case I thought it best to put all options on the table. – GWLlosa Mar 26 '15 at 21:39