your programing

.net의 app.config 또는 web.config에서 설정 읽기

lovepro 2020. 9. 29. 08:19
반응형

.net의 app.config 또는 web.config에서 설정 읽기


web.config또는 app.config파일 에서 설정을 읽을 수 있어야하는 C # 클래스 라이브러리에서 작업 중입니다 (DLL이 ASP.NET 웹 응용 프로그램 또는 Windows Forms 응용 프로그램에서 참조되는지 여부에 따라 다름).

나는 그것을 발견했다

ConfigurationSettings.AppSettings.Get("MySetting")

작동하지만 해당 코드는 Microsoft에서 더 이상 사용되지 않는 것으로 표시되었습니다.

다음을 사용해야한다고 읽었습니다.

ConfigurationManager.AppSettings["MySetting"]

그러나 System.Configuration.ConfigurationManager클래스는 C # 클래스 라이브러리 프로젝트에서 사용할 수없는 것 같습니다.

이것을 수행하는 가장 좋은 방법이 무엇인지 아는 사람이 있습니까?


프로젝트의 참조 폴더참조추가 해야 합니다 .System.Configuration

당신은 확실히 ConfigurationManager쓸모없는 ConfigurationSettings.


아래와 같은 샘플 App.config의 경우 :

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <appSettings>
    <add key="countoffiles" value="7" />
    <add key="logfilelocation" value="abc.txt" />
  </appSettings>
</configuration>

아래 표시된 코드를 사용하여 위의 앱 설정을 읽습니다.

using System.Configuration;

아직 참조 System.Configuration가없는 경우 프로젝트에 참조를 추가해야 할 수도 있습니다 . 그런 다음 다음과 같이 값에 액세스 할 수 있습니다.

string configvalue1 = ConfigurationManager.AppSettings["countoffiles"];
string configvalue2 = ConfigurationManager.AppSettings["logfilelocation"];

도움이 되었기를 바랍니다!


프레임 워크 4.5 및 4.6 업데이트; 다음은 더 이상 작동하지 않습니다.

string keyvalue=System.Configuration.ConfigurationManager.AppSettings["keyname"];

이제 속성을 통해 설정 클래스에 액세스합니다.

string keyvalue= Properties.Settings.Default.keyname;

자세한 내용은 응용 프로그램 설정 관리 를 참조하십시오.


클래스 라이브러리를 마우스 오른쪽 버튼으로 클릭하고 메뉴에서 "참조 추가"옵션을 선택합니다. 마지막으로 .NET 탭에서 System.Configuration을 선택합니다. 여기에는 프로젝트에 System.Configuration dll이 포함됩니다.


나는 이것을 사용하고 그것은 나를 위해 잘 작동합니다.

textBox1.Text = ConfigurationManager.AppSettings["Name"];

구성에서 읽기 :

Config에 대한 참조를 추가해야합니다.

  1. 프로젝트에서 "속성"을 엽니 다.
  2. "설정"탭으로 이동
  3. "이름"및 "값"추가
  4. 다음 코드를 사용하여 가치를 얻으십시오.

    문자열 값 = Properties.Settings.Default.keyname;

구성에 저장 :

   Properties.Settings.Default.keyName = value;
   Properties.Settings.Default.Save();

System.Configuration 어셈블리에 대한 참조를 프로젝트에 추가해야합니다.


App.config 파일을 DLL에 추가 할 수 있습니다. App.Config는 모든 dll이 실행중인 exe의 구성 파일에서 구성을 가져 오므로 실행 가능한 프로젝트에서만 작동합니다.

솔루션에 두 개의 프로젝트가 있다고 가정 해 보겠습니다.

  • SomeDll
  • SomeExe

귀하의 문제는 App.config를 SomeExe가 아닌 SomeDLL에 포함한다는 사실과 관련이있을 수 있습니다. SomeDll은 SomeExe 프로젝트에서 구성을 읽을 수 있습니다.


이 시도:

string keyvalue=System.Configuration.ConfigurationManager.AppSettings["keyname"];

web.config에서 다음 구조 여야합니다.

<configuration>
<appSettings>
<add key="keyname" value="keyvalue" />
</appSettings>
</configuration>

나는 똑같은 문제가 있었고 다음과 같이 읽으십시오.

System.Configuration.ConfigurationSettings.AppSettings["MySetting"]

web.config웹 애플리케이션과 함께 사용됩니다. web.config기본적으로 웹 애플리케이션에 필요한 여러 구성이 있습니다. web.config웹 응용 프로그램에서 각 폴더에 대해 가질 수 있습니다 .

app.configWindows 응용 프로그램에 사용됩니다. vs.net에서 애플리케이션을 빌드하면 자동으로로 이름 <appname>.exe.config변경되며이 파일은 애플리케이션과 함께 제공되어야합니다.

동일한 방법을 사용하여 app settings두 구성 파일 을 호출 할 수 있습니다 .

System.Configuration.ConfigurationSettings.AppSettings["Key"]

System.Configuration에 대한 래퍼 클래스를 아래와 같이 만들어 체계적으로 앱 설정 변수에 액세스하는 가장 좋은 방법을 찾았습니다.

public class BaseConfiguration
    {
        protected static object GetAppSetting(Type expectedType, string key)
        {
            string value = ConfigurationManager.AppSettings.Get(key);
            try
            {
                if (expectedType == typeof(int))
                    return int.Parse(value);
                if (expectedType == typeof(string))
                    return value;

                throw new Exception("Type not supported.");
            }
            catch (Exception ex)
            {
                throw new Exception(string.Format("Config key:{0} was expected to be of type {1} but was not.",
                    key, expectedType), ex);
            }
        }
    }

이제 아래와 같이 다른 클래스를 사용하여 하드 코딩 된 이름으로 필요한 설정 변수에 액세스 할 수 있습니다.

public class ConfigurationSettings:BaseConfiguration
    {
        #region App setting

        public static string ApplicationName
        {
            get { return (string)GetAppSetting(typeof(string), "ApplicationName"); }
        }

        public static string MailBccAddress
        {
            get { return (string)GetAppSetting(typeof(string), "MailBccAddress"); }
        }

        public static string DefaultConnection
        {
            get { return (string)GetAppSetting(typeof(string), "DefaultConnection"); }
        }

        #endregion App setting

        #region global setting



        #endregion global setting
    }

I strongly recommend you to create a Wrapper for this call. Something like a ConfigurationReaderService and use dependency injection to get this class. This way you will be able to isolate this configuration files for test purposes.

So use the ConfigurationManager.AppSettings["something"]; suggested and return this value. You can with this method create some kind of default return if there is no key available in .config file.


Also, you can use formo:

Config:

<appSettings>
    <add key="RetryAttempts" value="5" />
    <add key="ApplicationBuildDate" value="11/4/1999 6:23 AM" />
</appSettings>

Code:

dynamic config = new Configuration();
var retryAttempts1 = config.RetryAttempts;                 // returns 5 as a string
var retryAttempts2 = config.RetryAttempts(10);             // returns 5 if found in config, else 10
var retryAttempts3 = config.RetryAttempts(userInput, 10);  // returns 5 if it exists in config, else userInput if not null, else 10
var appBuildDate = config.ApplicationBuildDate<DateTime>();

Just for completeness, there's another option available for web projects only:

System.Web.Configuration.WebConfigurationManager.AppSettings["MySetting"]

The benefit of this is that it doesn't require an extra reference to be added so may be preferable for some people.


I always create an IConfig interface with typesafe properties declared for all configuration values. A Config implementation class then wrappers the calls to System.Configuration. All your System.Configuration calls are now in one place so much easier and cleaner to maintain and track which fields are being used and declare their default values. I write a set of private helper methods to read and parse common data types.

Using an IoC framework you can access the IConfig fields anywhere your in app by simply passing the interface to a class constructor. You're also then able to create mock implementations of the IConfig interface in your unit tests so you can now test various configuration values and value combinations without needing to touch your App.config or Web.config file.


Step 1: Right-click on references tab to add reference.

Step 2: Click on Assemblies tab

Step 3: Search for 'System.Configuration'

Step 4: Click OK.

Then It will work

 string value = System.Configuration.ConfigurationManager.AppSettings["keyname"];

I have been trying to find a fix for this same issue for a couple days now. I was able to resolve this by adding a key within the appsettings tag in the web.config. This should override the .dll when using the helper.

<configuration>
<appSettings>
<add key="loginUrl" value="~/RedirectValue.cshtml" />
<add key="autoFormsAuthentication" value="false"/>
</appSettings>
</configuration>

Another possible solution:

var MyReader = new System.Configuration.AppSettingsReader();
string keyvalue = MyReader.GetValue("keyalue",typeof(string)).ToString();

you can use below line, in my case it was working:

System.Configuration.ConfigurationSettings.AppSettings["yourKeyName"]

you must take care that above line of code is also old version and its deprecated in new libraries.


Pls check .net version you are working. It should be higher than 4. And you have to add System.Configuration system library to your application


The ConfigurationManager is not what you need to access your own settings

To do this you should use the

{YourAppName}.Properties.Settings.{settingName}


I was able to get below approach working for .netcore projects:

Steps :

i) Create an appsettings.json ( format given below ) in your project ii) Next create a configuration class, the format provided below. iii) I have created a Login() method to show the usage of the Configuration Class.

Create appsettings.json in your project with content :
`
{
  "Environments": {
    "QA": {
      "Url": "somevalue",
 "Username": "someuser",
      "Password": "somepwd"
  },
  "BrowserConfig": {
    "Browser": "Chrome",
    "Headless": "true"
  },
  "EnvironmentSelected": {
    "Environment": "QA" 
  }
}
`


`
 public static class Configuration
    {
        private static IConfiguration _configuration;

        static Configuration()
        {
            var builder = new ConfigurationBuilder()
                .AddJsonFile($"appsettings.json");

            _configuration = builder.Build();

        }
        public static Browser GetBrowser()
        {

            if (_configuration.GetSection("BrowserConfig:Browser").Value == "Firefox")
            {
                return Browser.Firefox;
            }
            if (_configuration.GetSection("BrowserConfig:Browser").Value == "Edge")
            {
                return Browser.Edge;
            }
            if (_configuration.GetSection("BrowserConfig:Browser").Value == "IE")
            {
                return Browser.InternetExplorer;
            }
            return Browser.Chrome;
        }

        public static bool IsHeadless()
        {
            return _configuration.GetSection("BrowserConfig:Headless").Value == "true";
        }

        public static string GetEnvironment()
        {
            return _configuration.GetSection("EnvironmentSelected")["Environment"];
        }
        public static IConfigurationSection EnvironmentInfo()
        {
            var env = GetEnvironment();
            return _configuration.GetSection($@"Environments:{env}");
        }

    }
`


`
 public void Login()
        {
            var environment = Configuration.EnvironmentInfo();
            Email.SendKeys(environment["username"]);
            Password.SendKeys(environment["password"]);
            WaitForElementToBeClickableAndClick(_driver, SignIn);
        }
`

here's an example: App.config

<applicationSettings>
        <MyApp.My.MySettings>
            <setting name="Printer" serializeAs="String">
                <value>1234 </value>
            </setting>
        </MyApp.My.MySettings>
    </applicationSettings>
Dim strPrinterName as string= My.settings.Printer

참고URL : https://stackoverflow.com/questions/1189364/reading-settings-from-app-config-or-web-config-in-net

반응형