0

I've been teaching myself how to code lately because I am bored. I am trying to load an XML file on startup and put the contents of that file into a listbox, then save the contents of the listbox to the file on close. That's exactly what I have now. However I want to be able to load from AppData as well as save back to the AppData folder without having to type the full path. I've tried using "%AppData%/Roaming/MyApp/data.xml" but that does not work and throws a exception.

Here is what I have now:

StreamReader sr = new StreamReader("data.xml");
            line = sr.ReadLine();
            while (line != null) {
                Streamers.Items.Add(line);
                line = sr.ReadLine();
            }
            Streamers.DataSource = line;
            Streamers.Sorted = true;
            sr.Close();
            Console.ReadLine();
dda
  • 6,030
  • 2
  • 25
  • 34

1 Answers1

2

You can use GetFolderPath

string path = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);

Also you can check this answer for more information.

Update

Notice that you need Administrator rights to access this folder.

For Access denied error check these two answers:

Number one

The directory %AppData% is a system-protected directory. Windows will try to block any access to this directory as soon as the access was not authorized (An access from another user than the Administrator).

Number two

I would use System.IO.Path.Combine(...) instead of string.Conact(...) in this situation. Like this...

string path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
"Programım");
Ghasem
  • 14,455
  • 21
  • 138
  • 171
  • I managed to create a folder however I cannot save the XML there. I get an access is denied exception. – Jarrett Mitchell Nov 21 '15 at 05:55
  • Alright. I managed to write to the AppData folder. Much thanks. Now how do I read from there? Beforehand, I just used StreamReader sr = new StreamReader("data.xml"); which only just read the locally found one and not the one in appdata – Jarrett Mitchell Nov 21 '15 at 06:32
  • @JarrettMitchell try `string path = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData); StreamReader sr = new StreamReader(path+"\\data.xml");` – Ghasem Nov 21 '15 at 07:05