Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Folder to store data files locally in WPF application

Tags:

c#

directory

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);
        }
like image 851
Beerlol Avatar asked Mar 11 '12 21:03

Beerlol


People also ask

Where can I find application data?

Every Windows Operating System contains a folder called AppData - short for Application Data. The AppData folder in Windows 10 is a hidden folder located in C:\Users\<username>\AppData. It contains custom settings and other information that PC system applications need for their operation.

How do I drag and drop files in WPF?

In the drop target, create a Drop event handler to process the dropped data. In the Drop event handler, extract the data from the DragEventArgs by using the GetDataPresent and GetData methods. In the Drop event handler, use the data to perform the desired drag-and-drop operation.


2 Answers

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

like image 105
Ralf de Kleine Avatar answered Sep 17 '22 13:09

Ralf de Kleine


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.

like image 21
Matt Burland Avatar answered Sep 16 '22 13:09

Matt Burland