.Net → C# – Read Configuration File from Another Running Application
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.
try
{
if (p.ProcessName == "myApplicationName")
{
exePath = p.MainModule.FileName;
break;
}
}
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.