How to Set the Configuration File to current dll.config - c#

When I start my exe , the configuration file is set to mypp.exe.config.
After certian point , I want it to point to mydll.config.
I am trying with:
var configPath = AppDomain.CurrentDomain.SetupInformation.ConfigurationFile;
var Location = Assembly.GetExecutingAssembly().Location;
AppDomain.CurrentDomain.SetupInformation.ConfigurationFile = config.FilePath;
But when I set a break point to see, the Configuration file is still set to myapp.exe.config.
What's missing?

Use AppDomain.SetData:
AppDomain.CurrentDomain.SetData("APP_CONFIG_FILE", config.FilePath);
I can't find any documentation for that, but it worked for me.

Related

how to read a file from a different project?

how to read a file from a different project?
I have a solution:
Solution1
-MyProject
-MyProject.Artifacts
----Message.XML
-MyProject.Tests
I am attempting to read the contents of Message.XML from MyProject.Tests.
How do I read the contents of Message.XML from MyProject.Tests?
Unfortunately, right now I'm doing something like this, but it's not very pretty:
var currentDir = Directory.GetCurrentDirectory();
var parentDir = Directory.GetParent(Directory.GetParent(currentDir).FullName).FullName;
var parentParentDir = Directory.GetParent(Directory.GetParent(Directory.GetParent(currentDir).FullName).FullName).FullName;
var parentParentParentDir = Directory.GetParent(Directory.GetParent(Directory.GetParent(Directory.GetParent(currentDir).FullName).FullName).FullName).FullName;
You can store a path to the file in app settings of app.config / web.config using that read the file contents.
That way if you need to deploy your software in a different way you have the flexibility
If your path is fixed, you can write the path like "c:\projects\solution ... Message.xml"
If you want a relative path, the simplest way is this:
var DI = new DirectoryInfo("..\\..\\..\\..\\Your Folder\\Message.XML");
This path is started from CurrentDirectory and goes four folders up and the one folder down and finds the file.

How can I properly reference this config file so I'm not hard coding the path?

Im trying to reference this config file that is in the same folder as the class that contains this code. I'd like to do some type of relative reference to it, so I can use it from other places. When I try using just the file name without the path, the application doesn't find the file. I debugged and the folder it seems to be looking in IIS folder which makes sense as Im using it in an IIS hosted wcf service. Anyways, how I can properly reference this config file without hard coding the path? So it looks in the project location. Thanks for any help. Have a great weekend!
public void Init()
{
var fileMap = new ExeConfigurationFileMap { ExeConfigFilename = #"C:\workspace\new\UnityDemo-v1.0.0.1\src\Core\unity.config" };
Configuration configuration = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);
var unitySection = (UnityConfigurationSection)configuration.GetSection("unity");
_container = new UnityContainer().LoadConfiguration(unitySection);
}
Cheers,
~ck
Using config files with services hosted in IIS is tricky, because the application directory is the one IIS runs in and that will be heavily protected against placing any files there. There may be other ways but for me it works to name the file web.config and copy it to the directory the .svc file resides in and then you can read the settings directly without having to reference the config file. I do not know of any way to do this copying from within the program itself. The installer will be able to do it though.
See: this question
Use Application.StartupPath to get the path the application started in then simply combine with the filename to get the full path:
var filePath = Path.Combine(Application.StartupPath, "unity.config");
var fileMap = new ExeConfigurationFileMap { ExeConfigFilename = filePath };
This will work only in winforms.
Another option is to use Environment.CurrentDirectory - by default it will be set to the process startup directory. Note that this property is mutable:
var filePath = Path.Combine(Environment.CurrentDirectory, "unity.config");
var fileMap = new ExeConfigurationFileMap { ExeConfigFilename = filePath };
Another option that worked for me in .NET is using Server.MapPath. This returns the full path of the given relative virtual path in the web application.
var filePath = Server.MapPath("/unity.config")
This physical file path can then be used to create the file map as above.

How to read user settings in app.config from a diff app?

I have a WinForms .exe with an App.config that has a bunch of User Scoped Settings that are set at runtime and saved.
I want to be able to use the WinForms app to change and save the settings and then click on button to do some work based on the those settings.
I also want to read the user settings in the same .config file from a sep. console app so I can schedule to work to be done as a scheduled task.
What is the best way to be able to do this?
Update:
I tried the reccommendation of using ConfigurationManager.OpenExeConfiguration as described in some of the answers like so.
Configuration config = ConfigurationManager.OpenExeConfiguration("F:\\Dir\\App.exe");
but when I try to retrieve a User Setting like so.
string result = config.AppSettings.Settings["DB"].ToString();
I get a Null reference error.
From code in the exe however the following correctly returns the DB name.
Properties.Settings.Default.DB
Where am I going wrong?
Update 2:
So based on some of the answers below I now can use the following to retrieve the raw XML of the section of the user.config file I am interested in from sep. ConsoleApp.
System.Configuration.ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap();
fileMap.ExeConfigFilename = #"D:\PathHere\user.config";
Configuration config = ConfigurationManager.OpenMappedExeConfiguration(fileMap,ConfigurationUserLevel.None);
System.Configuration.DefaultSection configSection = (System.Configuration.DefaultSection)config.GetSection("userSettings");
string result = configSection.SectionInformation.GetRawXml();
Console.WriteLine(result);
But I am still unable to just pull the value for the specific element I am interested in.
this should do it :
var clientSettingsSection = (System.Configuration.ClientSettingsSection)(ConfigurationManager.GetSection("userSettings/YourApplicationName.Properties.Settings"));
var setting = clientSettingsSection.Settings.Get("yourParamName_DB_");
string yourParamName_DB = ((setting.Value.ValueXml).LastChild).InnerText.ToString();
You can use the ConfigurationManager class to open the configuration file of another executable.
Configuration conf = ConfigurationManager.OpenExeConfiguration(exeFilePath);
// edit configuration settings
conf.Save();
See ConfigurationManager.OpenExeConfiguration
If you are setting these values per user basis you may need to use the ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel) method instead of the current method you are using now.
ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap();
fileMap.ExeConfigFilename = Environment.CurrentDirectory + "\\MyApp.exe.config";
//i have config in the same directory as my another app
System.Configuration.Configuration config = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);
var settingsSection = (System.Configuration.ClientSettingsSection)config.GetSection("userSettings/MyApp.Properties.Settings");
var setting = settingsSection.Settings.Get("MySetting");
var param = ((setting.Value.ValueXml).LastChild).InnerText.ToString();
If you know the path to the config file try:
System.Configuration.Configuration config = System.Configuration.ConfigurationManager.OpenExeConfiguration("configPath");
string myValue = config.AppSettings.Settings[ "myValue" ].Value;

ConfigurationManager.OpenExeConfiguration - loads the wrong file?

I have added multiple app.config (each with a differet name) files to a project, and set them to copy to the output directory on each build.
I try and access the contents of each file using this:
System.Configuration.Configuration o = ConfigurationManager.OpenExeConfiguration(#"app1.config");
The code runs, but o.HasFile ends up False, and o.FilePath ends up "app1.config.config". If I change to code:
System.Configuration.Configuration o = ConfigurationManager.OpenExeConfiguration(#"app1");
Then the code bombs with "An error occurred loading a configuration file: The parameter 'exePath' is invalid. Parameter name: exePath".
If I copy/paste the config file (so I end up with app1.config and app1.config.config) then the code runs fine, however, I posit this is not a good solution. My question is thus: how can I use ConfigurationManager.OpenExeConfiguration to load a config file corretly?
I can't remember where I found this solution but here is how I managed to load a specific exe configuration file:
ExeConfigurationFileMap map = new ExeConfigurationFileMap { ExeConfigFilename = "EXECONFIG_PATH" };
Configuration config = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None);
According to http://social.msdn.microsoft.com/Forums/en-US/winforms/thread/3943ec30-8be5-4f12-9667-3b812f711fc9 the parameter is the location of an exe, and the method then looks for the config corresponding to that exe (I guess the parameter name of exePath makes sense now!).
To avoid this problem altogether, you can read in the config file as an XML file, for example:
using System.Xml;
using System.Xml.XPath;
XmlDocument doc = new XmlDocument();
doc.Load(System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + "\\..\\..\\..\\MyWebProject\\web.config");
string value = doc.DocumentElement.SelectSingleNode("/configuration/appSettings/add[#key='MyKeyName']").Attributes["value"].Value;
using System.Reflection;
try
{
Uri UriAssemblyFolder = new Uri(System.IO.Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase));
string appPath = UriAssemblyFolder.LocalPath;
//Open the configuration file and retrieve
//the connectionStrings section.
Configuration config = ConfigurationManager.
OpenExeConfiguration(appPath + #"\" + exeConfigName);
ConnectionStringsSection section =
config.GetSection("connectionStrings")
as ConnectionStringsSection;
}
At least, this is the method I use when encrypting and decrypting the connectionStrings section for my console/GUI apps. exeConfigName is the name of the executable including the .exe.

FileInfo compact framework 3.5 - cannot find file

I am using the FileInfo class. However, the file info cannot find the file.
The file is called log4Net.config and I have added it to my project. I have set the properties to build action = 'Content' and copy output = 'copy always'
When I run the following code:
FileInfo logfileInfo = new FileInfo("Log4Net.config");
if (!logfileInfo.Exists)
{
Console.WriteLine("Cannot find file: " + logfileInfo.FullName);
return;
}
else
{
XmlConfigurator.Configure(logfileInfo);
}
Exists is always false. The exception is: Could not find file 'Log4Net.config'.
I have checked on my PDA and the Log4Net.config has been copied the PDA and is in the same directory as the executable. So not sure why it cannot find it.
Just some extra info the configure method expects a FileInfo as a parameter.
Am I doing something wrong.
Many thanks for any advice,
Steve
You have to point to the root of your project. FileInfo points to the root of the OS not the root of the exe. So you should change the code like this :
FileInfo logfileInfo = new FileInfo(Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase) + #"\Log4Net.config");
A file not found exception is also thrown when the program does not have the security permission to access the file, so perhaps that's the case?
btw, there's a contradiction in your Post: First you say the file is called "logPDA.config", then it's suddenly called "Log4Net.config". Just to make sure, is the file always named the same?
You are assuming that the Program Folder is the current directory. Afaik that is not the case. You can investigate starting with System.IO.Directory.GetCurrentDirectory()
string logIOFilePath =
Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase),
"Log4Net.config");

Categories

Resources