Beerlol
Beerlol

Reputation: 357

Folder to store data files locally in WPF application

I currently have the code below in my WPF application which does exactly what I want it to do, however, upon publishing this it won't necessarily be able to access these folder locations as they won't be pointing to the correct directory nor will the folders exist.

I was hoping somebody might be able to tell me what is the best way to save something into a local folder?

Whether it's inside the application folder itself or not is of no issue either.

The code I'm currently using for the writing of the file:

using (Stream stream = File.Open(@"..\..\Templates\data.bin", FileMode.Create))
            {
                BinaryFormatter bin = new BinaryFormatter();
                bin.Serialize(stream, templateList);
            }

The code I'm currently using for the loading of the file:

using (Stream stream = File.Open(@"..\..\Templates\data.bin", FileMode.Open))
        {
            BinaryFormatter bin = new BinaryFormatter();

            templateList = (List<Template>)bin.Deserialize(stream);
        }

Upvotes: 20

Views: 22819

Answers (2)

Ralf de Kleine
Ralf de Kleine

Reputation: 11756

You could use System.Environment.SpecialFolder.LocalApplicationData to store application specific data:

using System;

class Sample 
{
    public static void Main() 
    {
          Console.WriteLine("GetFolderPath: {0}", 
                 Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData));
    }
}

Ref: http://msdn.microsoft.com/en-us/library/system.environment.specialfolder.aspx

Upvotes: 21

Matt Burland
Matt Burland

Reputation: 45155

You can use Environment.SpecialFolder to find an appropriate place to put files (for example, ApplicationData would be a good place to start). If you only need a temp file, you can use Path.GetTempFileName to create one.

Edit: One last note. Storing stuff in the application folder itself can be a giant pain. Usually the application folder is created with the admin account during the installation so your app won't be able to write to it while running on a user account.

Upvotes: 21

Related Questions