Search code examples
c#wpffilepathsolutionstoring-data

How can I access a local folder inside a WPF project to load and store files?


I need a library of vector files, where the same files have to be used every time. I want to load them from a folder and have the option to store new ones.

I tried having a library folder inside the WPF project that contains the files: Solution/Project/Library/file1.dxf I load them like this:

string currentDir = Directory.GetCurrentDirectory();
var cutOff = currentDir.LastIndexOf(@"\bin\");
var folder = currentDir.Substring(0, cutOff) + @"\Library\";

string[] filePaths = Directory.GetFiles(folder, "*.dxf");

This worked when running on the PC the project was buid, but the program crashes when the .exe is run on another PC. How do I fix this or is there a better approach to this?


Solution

  • Create a subfolder under Environment.SpecialFolder.ApplicationData, read the files in the library folder if it exists. If not create it and save the existing library files to it (here from resources):

    string appFolder = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
    string path = appFolder + @"\MyAppLibrary\";
    
    if (!Directory.Exists(path))
    {
        Directory.CreateDirectory(path);
    
        // Add existing files to that folder
        var rm = Properties.Resources.ResourceManager;
        var resSet = rm.GetResourceSet(CultureInfo.CurrentUICulture, true, true);
        foreach (var res in resSet)
        {
            var entry = ((DictionaryEntry)res);
            var name = (string)entry.Key;
            var file = (byte[])rm.GetObject(name);
    
            var filePath = path + name + ".dxf";
            File.WriteAllBytes(filePath, file);
        }
    }
    
    // Load all files from the library folder
    string[] filePaths = Directory.GetFiles(path, "*.dxf");
    

    Thanks Jonathan Alfaro and Clemens!