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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With