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

I'm new to C # and am still in the process of figuring out best practices for certain things.

I want to know where I can store parameters such as paths (for file uploads, for example) and other various 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 for storing these parameters?

+3


source to share


1 answer


You'd better keep this in web.config

, as this can be changed after compilation.

The item is appSettings

reserved for this function. You can even separate this part in another file to make it perfectly clear in your specific configuration.

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 separate appSettings.xml

:

<?xml version="1.0" encoding="utf-8" ?>
<appSettings>
    <add key="DocumentDirectory" value="~/Documents" />
</appSettings>

      

You can read these 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;
    }
}

      

+7


source







All Articles