Page 1 of 1

Read Configuration File from Another Running Application

#1 eclipsed4utoo  Icon User is offline

  • Not Your Ordinary Programmer
  • member icon

Reputation: 1532
  • View blog
  • Posts: 5,969
  • Joined: 21-March 08

Posted 11 August 2010 - 07:59 AM

I recently was writing an small application that would be running in the background to complement my main application that users were going to be interacting with. Both applications would be connecting to a database, so I needed a connection string that was configurable by users. In my main application, I already had this working fine. However, I didnít want the users to have to configure both applications. So I decided that I was just going to read the app.config file of my main application and use itís connection string for the application running in the background.

This is how I accomplished it.

So first, I need to get the startup location of my main application. It could be installed anywhere, so I canít hard-code the path. I also know that the main application will always be running. So I use the Process class to get an array of the current processes running on the machine. I then loop through those processes, looking for the process that has the name of my application.

// Add these using statements at the top of the code page(if not already there)
using System.Configuration;
using System.Diagnostics;

string exePath = string.Empty;
Process[] processes = Process.GetProcesses();

// Alternatively, this could have also been used
// Process[] processes = Process.GetProcessesByName("myApplicationName");

foreach (Process p in processes)
     // try/catch was used because some applications threw a "Access Denied"
     //     when trying to read it's filename.
        if (p.ProcessName == "myApplicationName")
             exePath = p.MainModule.FileName;
     catch {}

Now I need to read the configuration file for the applicationís exe.

string connectionString = string.Empty;

Configuration config = ConfigurationManager.OpenExeConfiguration(exePath);
KeyValueConfigurationCollection col = config.AppSettings.Settings;
connectionString = col["Main.ConnectionString"].Value;

And thatís all I needed to do. Now my users only need to configure the main application, and I can still connect to the database using both applications.

Is This A Good Question/Topic? 0
  • +

Page 1 of 1