Search code examples
wpfdirectoryworking-directory

WPF set the working directory before anything else


i have a wpf-application. in the constructor of the mainviewmodel i set the working directory like this:

// get the current dircetory and move one folder up
Directory.SetCurrentDirectory(@"..\");
// check if the folder 'Data' already exist, otherwise create it
if (!Directory.Exists(Path.Combine(Directory.GetCurrentDirectory(), "Data")))
{
    Directory.CreateDirectory(Path.Combine(Directory.GetCurrentDirectory(), "Data"));
}
// set the directory to the folder 'Data'
Directory.SetCurrentDirectory(Path.Combine(Directory.GetCurrentDirectory(), "Data"));

in some of the other viewmodels, i read data in the constructor. but at this time, the working directory is not set. how can i set the directory before all the other viewmodels are created?

this is how i instantiate the VMs:

readonly static HomeViewModel homeViewModel = new HomeViewModel();

Solution

  • You can create a custom application startup handler and do what you want before creating any views.

    public partial class App : Application
    {
        void App_Startup(object sender, StartupEventArgs e)
        {
            // Do your working directory setup here
    
            // Create main application window, starting minimized if specified
            MainWindow mainWindow = new MainWindow();
            mainWindow.Show();
        }
    }