Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where to store global variables (like paths) in C#?

Tags:

c#

asp.net

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?

like image 246
Jack Zach Tibbles Avatar asked Mar 19 '23 13:03

Jack Zach Tibbles


1 Answers

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;
    }
}
like image 165
Patrick Hofman Avatar answered Apr 02 '23 09:04

Patrick Hofman