Search code examples
.netapp-configspecial-folders

App.config My Documents macro


I am trying to include a substitution in a connection string, so that rather than referring to C:\Users\<myid>\Documents, I can leave user-specific information out of it and let the application dynamically resolve the path. I saw in an answer to another SO question that application data can be referenced with ${AppData}, but I have thus far not found a similar variable/macro for referencing the Documents folder, or even the base user folder. I've tried ${MyDocuments} and ${Documents}, but to no avail, and I cannot find a list anywhere containing all of the possibilities. Is there a way to do this without writing custom configuration code? I'm not opposed to that if it's the only way to go; however, I'd rather use a baked-in solution if one exists.


Solution

  • The provided indirection is |DataDirectory|, it is configured in the AppDomain. But that requires modifying a .config file, something that's pretty reasonable for a server-style app but not the kind of thing you'd be looking for if you just want to pick up the file from the user's home directory.

    The simplest way to go about it is to just format the string at runtime. You can specify the connection string in an application setting like this:

    Server=.\SQLExpress;AttachDbFilename={0}\MyDataFile.mdf;Database=dbname
    

    Note the {0}, that lets you insert the directory with String.Format():

        var homedir = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
        var connstr = string.Format(Properties.Settings.Default.ConnectionString, homedir);
    

    And you still have a backdoor when the user wants a completely different location, he simply changes the app.exe.config file to the directory he wants.