I'm new to C# and am still in the process of figuring out the best practices for certain things.
I want to know where I could store settings such as paths (eg. For file uploads) and other assorted variables so that they can be accessed anywhere in the project.
Should I just create a class with static variables or is there a better approach to storing these settings?
You'd better save this in the web.config since this can be changed after compilation.
The appSettings element is reserved for this kind of functionality. You can even split this part off in a different file so it is totally clear this in your specific config.
Example web.config only:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="DocumentDirectory" value="~/Documents" />
</appSettings>
</configuration>
Or:
web.config:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings file="appSettings.xml" />
</configuration>
And a separate appSettings.xml:
<?xml version="1.0" encoding="utf-8" ?>
<appSettings>
<add key="DocumentDirectory" value="~/Documents" />
</appSettings>
You can read those settings like this:
using System.Configuration;
using System.Web.Configuration;
Configuration config = WebConfigurationManager.OpenWebConfiguration(null);
if (config.AppSettings.Settings.Count > 0)
{
KeyValueConfigurationElement customSetting = config.AppSettings.Settings["DocumentDirectory"];
if (customSetting != null)
{
string directory = customSetting.Value;
}
}
Related
Following config file causes error because of & in 'url' value:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key ="url" value ="http://www.example.com/?user=admin&password=1234"/>
</appSettings>
</configuration>
The question is which encoding to use for key/value in a config file ? (i.e Url Encoding ...)
This is an XML file. As such, you must XML-escape all reserved characters:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key ="url" value ="http://www.example.com/?user=admin&password=1234"/>
</appSettings>
</configuration>
Programmatically you can perform this type of escaping using the System.Web.HttpUtility.HtmlEncode method. Yes, its name suggests HTML specific encoding, but in my experience this is equivalent to XML escaping.
I need to read web.config file, outside the application's folder (located in any other directory).
I tried this code:
string filePath = #"C:\Users\Idrees\Downloads\New folder\Web.config";
Configuration c1 = ConfigurationManager.OpenExeConfiguration(filePath);
var value1 = c1.AppSettings.Settings["Key1"].Value;
But it is giving me the error:
Object reference not set to an instance of an object.
Because here, c1.AppSettings is an object, but c1.AppSettings.Settings contains not items (hence 0 Count). It is not really loading the AppSettings keys. When trying to read any Key from Settings collection, it gives this error.
Is there any way how to load AppSettings keys from a web.config file outside the application folder.
If I put same file within application folder, then it reads the keys successfully.
This is my sample config file's content:
<?xml version="1.0" encoding="utf-8"?>
<!--
For more information on how to configure your ASP.NET application, please visit
http://go.microsoft.com/fwlink/?LinkId=169433
-->
<configuration>
<connectionStrings>
<!--here goes my connection strings-->
</connectionStrings>
<appSettings>
<add key="Key1" value="Value1" />
<add key="Key2" value="Value2" />
<add key="Key3" value="Value3" />
</appSettings>
</configuration>
I have a web application already running on my server. And I need to develop a small utility which has to do some job in database, and I don't want to write db credentials or connection string(and some other additional app-settings) in each application, I want it to read same thing from web.config.
You can using ConfigurationManager to read arbitrary configuration files by opening a mapped exe configuration as follows:
var filePath = #"C:\Users\Idrees\Downloads\New folder\Web.config";
var fileMap = new ExeConfigurationFileMap { ExeConfigFilename = filePath };
var configuration = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);
var value = configuration.AppSettings.Settings["Key1"].Value;
As I understand from your comment you want some kind of shared configuration accross multiple app on the same computer. You may consider using external file like this :
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
<connectionStrings configSource="config\connString01.config"/>
<appSettings file="config\config01.config">
<add key="Var3" value="Var3 value from main config file"/>
</appSettings>
in above .config example connectionStrings is sourced from an other file. Below an example what can be such an external config file:
<connectionStrings>
<add name="SQLConnectionString01" connectionString="Data Source=sourcename01;Initial Catalog=cat01;Persist Security Info=True;Integrated Security=true;"/>
</connectionStrings>
Read documentation: ConfigurationManager.OpenExeConfiguration on MSDN
public static Configuration OpenExeConfiguration(
string exePath
)
This is EXE path
When I execute my app (Winform)from the computer where it was developed there is no error, but When I execute this in another computer I get the error. My App.config is like this:
<?xml version="1.0"?>
<configuration>
<appSettings>
<add key="SecurityKey"/>
</appSettings>
<startup>
<supportedRuntime version="v4.0"sku="...."/>
</startup>
</configuration>
and this is the line that I use:
string key = (string)settingsReader.GetValue("SecurityKey", typeof(String));
I already tried to follow this The key 'UserID' does not exist in the appSettings configuration section, but it is still the same.
Any suggestions?
the appSettings in the .config file is different from .settings file.
Take a look at ConfigurationManager.AppSettings Property.
I'd also mention that I have no idea how either the settingsReader nor the ConfigurationManager work with a key with no value:
<add key="SecurityKey"/> <!-- no value? -->
<add key="SecurityKeyWithValue" value="myvalue"/>
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="SecurityKey" value="Syed Moshiur Murshed"/>
</appSettings>
</configuration>
I've used the Configuration Section Designer (csd) to generate an xml configuration file to my application.
Now, I want to work with this xml file (on c#) and do 2 things:
1. read a specific value (searching by its field), something like
txtbox_username.Text = ConfigurationManager.AppSettings["userName"];
2. write a specific value, something like
config.AppSettings.Settings["userName"].Value = txtbox_username.Text;
config.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("configuration");
p.s: this is how i perform read/write for regular xml files that looks like this:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
add key="userName" value="Value1"
</appSettings>
</configuration>
but the csd generated xml looks different...
<?xml version="1.0"?>
<configuration>
<configSections>
<section name="sectionName" type="Sample.ConfigurationSection.sectionName, Sample.ConfigurationSection, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"/>
</configSections>
<sectionName xmlns="Sample.ConfigurationSection">
<logFile debugLevel="3" filePath="c:\new" maxFileCount="10" maxFileLength="1000"/>
<results path="C:\Results"/>
<details user="blabla" pass="12345" code="abc"/>
<stuff fromAddress="from#gmail.com" toAddress="to#gmail.com" sendMail="true""/>
</sectionName>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/>
</startup>
</configuration>
here, I want to edit and save, for example, user/pass/code fields.
In short (and using these extensions: http://searisen.com/xmllib/extensions.wiki) you can do this to read/write the user,
XElement file = XElement.Load(xmlFile);
XNamespace ns = "Sample.ConfigurationSection";
XElement section = file.GetElement(ns + "sectionName");
string user = section.Get("details/user", string.Empty);
section.Set("details/user", "bubba", true); // true = set as attribute
file.Save(xmlFile);
Following config file causes error because of & in 'url' value:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key ="url" value ="http://www.example.com/?user=admin&password=1234"/>
</appSettings>
</configuration>
The question is which encoding to use for key/value in a config file ? (i.e Url Encoding ...)
This is an XML file. As such, you must XML-escape all reserved characters:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key ="url" value ="http://www.example.com/?user=admin&password=1234"/>
</appSettings>
</configuration>
Programmatically you can perform this type of escaping using the System.Web.HttpUtility.HtmlEncode method. Yes, its name suggests HTML specific encoding, but in my experience this is equivalent to XML escaping.