Hi all,

Bit of a strange question but here goes...

In my App.Config, I have a few parameters set, like connection strings, that locate and use a database stored in the user's my documents folder -

<connectionStrings>
    <add name="DatabaseConnectionString" connectionString="Data Source=D\:My Stuff\Documents\My App\MyAppDatabase.sdf" />
  </connectionStrings>

I was wondering, rather than having to change the app.config each time I copy it to a new machine, is there some way of having it dynamically set, say something like

    <connectionStrings>
        <add name="DatabaseConnectionString" connectionString="Data Source=$(MyDocumentsFolder)\My App\MyAppDatabase.sdf" />
      </connectionStrings>

Or is this not possible at all?

Any help or pointers are much appreciated :)

It's not possible, but you could do it from code.

This is not an working code, just the logic idea:

string strConn = @"Data Source=$(MyDocumentsFolder)\My App\MyAppDatabase.sdf";
string strFlag = "$(MyDocumentsFolder)";

if ( strConn.IndexOf(strFlag) > 0 ) {
    strConn = strConn.Replace(strFlag, Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData));
}

Yeah I had something like that already, I get the connection string section from the code, replace thae portion of the connection string with the current documents folder then set the connection string and refresh it... just seemed a bit "hacky" in a way and was wondering if there was an easier way :)

Not really, MS designed it to be that way.

The only automatic substitution that I am aware of being allowed in a connection string is the "|DataDirectory|".

Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\Database1.accdb

The default definition for DataDirectory is the application directory, but this can be redefined like this:

AppDomain.CurrentDomain.SetData("DataDirectory", Environment.GetFolderPath(Environment.SpecialFolder.Personal));

The obvious caveat is to redefine it before trying to use the connection string to access the data.

Yeah I ended up just doing a Replace on the connection string, replacing it with the Environment.GetFolderPath.MyDocuments then refreshing the config section before starting any database work, just wondering if there was a quicker way cause I seen in things like the post/pre-build events you can call environment variables like $(USERPROFILE) and so on :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.