Get root config files path inside dll - c#

I have a (website|windows) app and a dll(classlibrary). i want to get the root(website|windows) config file path in the dll.
I tried ConfigurationManager.OpenExeConfiguration with different assembly.get's but they always giving the dll config path.
thanks

Hi found this and it works well
Configuration config;
if (System.Web.HttpContext.Current != null &&
System.Web.HttpContext.Current.Request.PhysicalPath.Equals(String.Empty) == false)
{
config = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration(HttpRuntime.AppDomainAppVirtualPath);
}
else
{
config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
}
Basicly it will get web.config if its a website and it will get app.exe.config if its a windows app

Related

C# - How to use another project logging configuration into current project?

I have 12 projects in my solution file. There are most Windows services (ServiceProj_1, ServiceProj_2, ...) and one project is of web application (WebApp). I use log4net for logging. WebApp and ServiceProject_1, ServiceProj_2, ... have log4net configuration into web.config and app.config files respectively. We have implemented a DMZ, so the WebApp is only exposed to the other people. Now there is a requirement to use logging of those windows service projects instead of WebApp.
I have come to know that I can create a custom appender and make it possible. The catch is, there are lots of lines already written into WebApp to log a LogMessage into log file so we cannot touch those lines.
I have no idea what to do and how to do. Need help.
If the description is not understandable then please let me know I will try to explain more.
You can specify the config file and load it dynamically...
Here my config file is found at the location of FullConfigFilePath.
private Configuration Config
{
get
{
if (_Config != null) return _Config;
_Config = ConfigurationManager.OpenMappedExeConfiguration(
new ExeConfigurationFileMap()
{
ExeConfigFilename = FullConfigFilePath
}, ConfigurationUserLevel.None);
return _Config;
}
}
Once the config is loaded you can access the values from there....
For instance.....
private string BaseUrl
{
get
{
return this.Config.AppSettings.Settings["MyConfigSetting"].Value;
}
}
Hopefully you can tweak and use this sort of approach for your needs.

Link to xml file searching for the file in the wrong place

Hi I seem to be having some problems when working with linq to xml.When I try to load the xml file in my code it seems LINQ is looking for it in C:\Program Files (x86)\IIS Express.
This is my code:
public static class ConfigurationData
{
public static string GetAssemblyName()
{
var assemblyName = from config in XDocument.Load(#"T4Config.xml").Descendants("dataService")
select config.Element("AssemblyProjectName").Value;
if (assemblyName != null)
{
return assemblyName.ToString();
}
return string.Empty;
}
}
Both the XML file and this class are in a folder called Controller details.When I try to load this method I get a file not found exception , BEcause linq is searching in C:\Program Files (x86)\IIS Express.
How can I make linq look for it in the same foldeR?
var assemblyName = from config in XDocument.Load(#"T4Config.xml").Descendants("dataService")
select config.Element("AssemblyProjectName").Value;
I am not sure how this is even getting to the folder you mentioned, as you have only specified a file name. Change XDocument.Load("file.xml") too XDocument.Load("YourFolder\YourSubFolder\YourFile.xml).
You can use Server.MapPath("/T4Config.xml")

exePath must be specified when not running inside a stand alone exe

When i am using a web application, the line of code below
Configuration objConfig =
ConfigurationManager.OpenExeConfiguration( ConfigurationUserLevel.None);
in class library are giving this error:
"exePath must be specified when not running inside a stand alone exe."
Previously a console application was being used, and the code could access the app.config. I tried using the System.Web.Configuration in class library but the dll was not present in the .Net tab for "Add reference".
Kindly help :)
You need to use a different configuration manager in a web context. The following code
block shows an example of how to deal with this:
System.Configuration.Configuration configuration = null;
if (System.Web.HttpContext.Current != null)
{
configuration =
System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~");
}
else
{
configuration =
ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
}
I'm not sure what you're doing; but at first glance it looks like you're trying to use code written for a WinForms application in a web environment. This almost certainly will not work, since your web app won't have the permissions you need.
Try looking up how to do this in a web environment (since you seem to be dealing with config files, try searching on WEB.CONFIG to start)
I tried to use the answer from #shane but ended up with the same exception using Hangfire. This code worked for me though:
System.Configuration.Configuration configFile = null;
if (System.Web.HttpContext.Current != null)
{
configFile =
System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~");
}
else
{
System.Configuration.ExeConfigurationFileMap map = new ExeConfigurationFileMap { ExeConfigFilename = $"{System.AppDomain.CurrentDomain.BaseDirectory}Web.Config" };
configFile = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None);
}
Note that editing Web.config will cause the application pool to restart!

How to run a executable program with different configuration file?

I want to run a program with different configuration file, the program write with C# 2.0, I make some different file name {program_name}.exe.config, I mean one exe with different config file, for example I have 3 config file, then I will run 3 exe with the different config file, bu the exe file is the same one.
Can I do not modify the program for read the different config file (I don`t want to put the config file path in the exe command parameters) to do that(like use the batch file or other method.) ?
Thanks.
You can change the configuration file for the application domain in which the exe is loaded. This is done using the SetData method of the AppDomain class. Ensure that this line of code is executed as the first line of your application.
I have used following code to share 1 exe.config file between 3 different executables.
AppDomain.CurrentDomain.SetData("APP_CONFIG_FILE","yourSharedConfig.exe.config");
You can look at the following blog entry
Binding to custom app.config
If you want to run the same exe with 3 different configs, I believe the same approach will work with bit of customization. You can pass the name of the config file while invoking the exe as a command line parameter and using the SetData method you can dynamically set the config.
I make it with LINQ and passing the parameter as config=path2file
public partial class App : Application {
private void startup(object sender, StartupEventArgs e) {
if (null != e) {
if (null != e.Args && 0 < e.Args.Length) {
string config = e.Args.Where(a => a.StartsWith("config=")).FirstOrDefault();
if (null != config) {
config = config.Substring("config=".Length);
if (File.Exists(config)) {
AppDomain.CurrentDomain.SetData("APP_CONFIG_FILE", config);
}
}
}
}
}
The main issue you have with three configs and one executable is that you need to specify to the executable which config to use.
One option is to make 3 copies of your executable, exe1.exe, exe2.exe and exe3.exe and have a similarly named config for each - exe1.exe.config, exe2.exe.config and exe3.exe.config.
When running each executable, it will use the correct config.
Another option is to have several batch files that will rename the different config files according to which one you want to use. Then you have a single exe and three configs.
You create a second executable, and always run that one first. In it, all you do is rename one configfile to the correct name and fire the main application.
string currentConfig = "application.exe.config";
string someOtherName = "firstconfig.config";
string configFileYouWant = "secondconfig.config";
string application = "application.exe";
File.Move(currentConfig, someOtherName);
File.Move(configFileYouWant, currentConfig);
Process.Start(application);

How do I specify the name of my application's App.config file in WPF?

This is very frustrating... I can set the Configuration File for a Windows Forms Application just fine. Consider this:
public static void Main(){
AppDomain.CurrentDomain.SetData("APP_CONFIG_FILE", #"SharedAppConfig.config");
//do other things
}
However, in a WPF application, this doesn't seem to work! If I set this value, the value of the AppDomain.CurrentDomain.SetupInformation.ConfigurationFile property is correct, but any calls to that configuration file while debugging yield no results. There are WCF configuration settings in an App.config that I need to share between application, so this is my proposed solution. Is it possible to dynamically set the location of my config file in WPF?
Help! Thanks!
You should be able to do something along the lines of:
using System.Configuration;
public class TryThis
{
Configuration config = ConfigurationManager.OpenExeConfiguration("C:\PathTo\app.exe");
public static void Main()
{
// Get something from the config to test.
string test = config.AppSettings.Settings["TestSetting"].Value;
// Set a value in the config file.
config.AppSettings.Settings["TestSetting"].Value = test;
// Save the changes to disk.
config.Save(ConfigurationSaveMode.Modified);
}
}
NOTE: This will attempt to open a file named app.exe.config at C:\PathTo. This also REQUIRES that a file exists at the same path with the name "app.exe". The "app.exe" file can just be an empty file though. For your case I'd almost make a shared "Config.dll" library that would handle the config file.
~md5sum~
Is this on the service side or the client side? If on the service side, it is often the case that the service is running in its own AppDomain, so that if you set AppDomain.CurrentDomain.SetData(...) it won't apply to the service configuration.
I'm not entirely sure how to get around this, but you should be able to control the service's configuration by implementing your own ServiceHost.

Categories

Resources