My config file is located here:
"~/Admin/Web.config"
I tried opening it via the below code but it didn't work:
var physicalFilePath = HttpContext.Current.Server.MapPath("~/Admin/Web.config");
var configMap = new ConfigurationFileMap(physicalFilePath);
var configuration = ConfigurationManager.OpenMappedMachineConfiguration(configMap);
var appSettingsSection = (AppSettingsSection)configuration.GetSection("appSettings");
when appsettings line runs, it throws the below error message:
Unable to cast object of type 'System.Configuration.DefaultSection' to type 'System.Configuration.AppSettingsSection'.
My Web.Config looks like below:
<?xml version="1.0"?>
<configuration xmlns="http://schemas.microsoft.com/.NetConfiguration/v2.0">
<appSettings>
<add key="AdminUsername" value="Test1"/>
<add key="AdminPassword" value="Test2"/>
</appSettings>
<connectionStrings></connectionStrings>
</configuration>
How could I get the appsettings?
For web-app, you need to use System.Web.Configuration.WebConfigurationManager class and no need to set absolute path.
var web=System.Web.Configuration.WebConfigurationManager
.OpenWebConfiguration("~/admin/web.config");
String appValue=web.AppSettings.Settings["key"].Value;
If you are looking for adding some stuff to the Web.config, and then reading it from the code.
What you need is Custom Configuration Sections in Web.config
Look here:
How do I define custom web.config sections with potential child elements and attributes for the properties?
and here:
Creating Custom Configuration Sections in Web.config - 4GuysFromRolla.com
Related
I'm using the AppSettingsReader() method to get a value from a given key in the app.config file:
var value = new AppSettingsReader().GetValue("SomeKey", typeof(string)) as string;
This is done in a class which is in a seperate assembly with its own app.config file. Now if I specify the key/value pair in this app.config:
<appSettings>
<add key="SomeKey" value="MyValue" />
</appSettings>
It throws the error:
"The key 'SomeKey' does not exist in the appSettings configuration section."
Because it looks in the App.config file from my main application which is, as stated before, in a different assembly. When I put my key/value pairs in there it works properly.
Is there a way of telling AppSettingsReader() to look in the app.config of the assembly from which it is called and not in the main (parent) assembly?
For this case you can use the ConfigurationManager class. It allows you to open configuration files from various places. To open a .config file, other than the one from the .exe, you could use the method OpenMappedExeConfiguration.
string pathToOtherConfigFile = ""; //you need to specify the path
ExeConfigurationFileMap configMap = new ExeConfigurationFileMap();
configMap.ExeConfigFilename = pathToOtherConfig;
Configuration config = ConfigurationManager.OpenMappedExeConfiguration(configMap, ConfigurationUserLevel.None);
var value = config.AppSettings["SomeKey"];
string appConfPath = Directory.GetParent(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)).FullName;
string fullPath = appConfPath + "\\Local\\RandFolder\\ThisOne\\application.settings.xml";
var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
config.AppSettings.File = fullPath;
config.AppSettings.Settings.Add("Password", "djydyjdjtdtyjddj");
config.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("appSettings");
var temp = config.AppSettings;
I am currently trying to set the "file" attribute of my appSettings configuration and reference XML's included settings at runtime. I am unable to do this before compile because the XML settings file will change based on the local machines settings.
However, after making the above changes, the temp variable only contains the "Password" item and is unable to retrieve the other settings located in the included file path. I know the file attribute is being set but for some reason the referenced setting are still hidden. The application.settings.xml file looks like this...
<?xml version="1.0" encoding="utf-8"?>
<appSettings>
<add key="ServerLocation" />
<add key="PerforceURI" value="yuhsgbyluvgblsg" />
</appSettings>
Any help is greatly appreciated!
I won't try to critique what you are doing, but provide you with a simple explanation of what you are seeing.
ConfigurationManager.RefreshSection refreshes the section in the Configuration instance used by the static ConfigurationManager. It does not effect the Configuration instance you created by calling OpenExeConfiguration; for that to occur you would need to call OpenExeConfiguration again.
I have a WinForm derived application (note NOT an ASP.NET web application) from where I need to modify a custom section of an arbitrary web.config file. As an example, if my web.config is something like this:
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<!-- General web.config stuff follows -->
<system.web>
<httpRuntime executionTimeout="110" maxRequestLength="1024" requestValidationMode="2.0" />
</system.web>
<MyConfigSection>
<GeneralParameters>
<param key="Var1" value="value1" />
</GeneralParameters>
</MyConfigSection>
</configuration>
I can easily modify some default parameter, say, for maxRequestLength I'd do this and it would work:
//Path to the web.config file
string strWebConfigFile = #"C:\My files\web.config";
//Convert absolute path to virtual
var configFile = new FileInfo(strWebConfigFile);
var vdm = new VirtualDirectoryMapping(configFile.DirectoryName, true, configFile.Name);
var wcfm = new WebConfigurationFileMap();
wcfm.VirtualDirectories.Add("/", vdm);
//Open web.config file
System.Configuration.Configuration config =
System.Web.Configuration.WebConfigurationManager.OpenMappedWebConfiguration(wcfm, "/");
if (config != null)
{
System.Configuration.ConfigurationSection system_web =
config.GetSection("system.web/httpRuntime");
PropertyInformation pi = system_web.ElementInformation.Properties["maxRequestLength"];
pi.Value = 1234; //Set new value
//Save
config.Save(ConfigurationSaveMode.Modified);
}
The issue is when I try to modify my custom section. Say, if I wanted to rewrite Var1 parameter's value with value2, the following:
System.Configuration.ConfigurationSection genParams = config.GetSection("MyConfigSection/GeneralParameters");
returns null and if I call it with just MyConfigSection, it gives me this exception:
An error occurred creating the configuration section handler for
MyConfigSection: Could not load type 'MyWebApp.Configuration' from
assembly 'System.Web, Version=4.0.0.0, Culture=neutral,
PublicKeyToken=N'.
What shall I do here to add that "configuration section handler"?
You have to open it up with XmlDocument, and work with it, sorry. That is how we cracked this nut - sorry I'm not at liberty to give you the code.
Is there a way to acomplish that? I know how to do it with the web.config file but I was told that cannot be in web.config cuz it must be in a text file where the connection string must be.
Here is what i have tried:
<configuration>
<connectionStrings configSource="ConexionBaseDeDatos.txt"></connectionStrings>
</configuration>
Similar like if i'd it use the a .config file like this
<configuration>
<connectionStrings configSource="ConexionBaseDeDatos.config"></connectionStrings>
</configuration>
And the base name
using System.Data.Entity;
namespace appSwicth.Models {
public class ConexionBaseDeDatos:DbContext {
DbContext db;
public ConexionBaseDeDatos() :base()
{
}
}
}
But I got an error:
"Root Element is missing"
And then the url of the file and nothing more.(the url is totally correct). In the txt file i have nothing now. Could that be the reason of why? I added a connectiong string to it but still not worked, maybe im doing something wrong.
Any way to solve this? If you need more, let me know.
Following is the Standard Format to mention the External Configuration file only.
<?xml version='1.0' encoding='utf-8'?>
<configuration>
<connectionStrings configSource="Your_File_Name.config"/>
</configuration>
It's self explanatory from it's name Config Source
The Source belongs to Configuration files only.
From MSDN - Storing and Retrieving Connection Strings
Alternative - From the above comments
Fetch the information from App Settings like below.
<add key="ConexionBaseDeDatos" value="ConexionBaseDeDatos.txt"/>
Is it possible to retrieve a custom configuration section from a config file other than the app.config or web.config.
I tried using the System.Configuration.ConfigurationManager's OpenExeConfiguration and GetSection method calls together but without luck. My intention is to define custom configuration sections for interchangeable process adapters and contain the custom config section in a separate config file other than app.config and web.config. I see plenty of examples for appsettings and connectionstrings.
static private DigiKeyReadTaskConfigSection digiKeyReadTaskConfigSection;
static DigiKeyReadTaskConfigSection DigiKeyReadTaskConfigSection {
get {
if (digiKeyReadTaskConfigSection == null) {
digiKeyReadTaskConfigSection = (DigiKeyReadTaskConfigSection)ConfigurationManager.OpenExeConfiguration("ReadTask.config").GetSection("DigiKeyReadTaskConfigSection");
}
return digiKeyReadTaskConfigSection;
}
}
The digiKeyReadTaskConfigSection = (DigiKeyReadTaskConfigSection)ConfigurationManager.OpenExeConfiguration call seems to be working however the (DigiKeyReadTaskConfigSection)ConfigurationManager.OpenExeConfiguration("ReadTask.config").GetSection("DigiKeyReadTaskConfigSection") returns null.
The ReadTask.config file lives in the bin file of the App:
<configuration> <configSections>
<section name="DigiKeyReadTaskConfigSection" type="DataReadInc.WebSiteRead.TaskConfigSection.DigiKeyReadTaskConfigSection, DataReadInc.WebSiteRead" />
<section name="ArrowReadTaskConfigSection" type="DataReadInc.WebSiteRead.TaskConfigSection.ArrowReadTaskConfigSection, DataReadInc.WebSiteRead" /> </configSections> <DigiKeyReadTaskConfigSection DigiKeySiteURL="http://search.digikey.com/scripts/DkSearch/dksus.dll?WT.z_header=search_go&lang=en&site=us&keywords="
SiteLogInURL="https://ordering.digikey.com/RegisteredUser/Login.aspx,formName=" SiteLoginId="X" SiteLoginPassword="X" /> <ArrowReadTaskConfigSection ArrowAmericaSiteURL="http://components.arrow.com/part/search/"
SiteLoginURL="http://components.arrow.com/login/processlogin#" SiteLoginId="X" SiteLoginPassword="X" /> </configuration>
I have seen this type of setup with Spring.Net and a J2EE implementation so I am sure it is possible. I can just put my custom config sections in the App.config or web.config file, however it would be significantly cleaner for them to exist in their own config file.
Use ConfigurationManager.OpenMappedExeConfiguration(). OpenExeConfiguration relates to a certain exe.