developer tip

Windows Forms C # 응용 프로그램에서 구성 파일을 사용하는 가장 간단한 방법

copycodes 2020. 9. 15. 07:56
반응형

Windows Forms C # 응용 프로그램에서 구성 파일을 사용하는 가장 간단한 방법


저는 .NET을 처음 접했고 여전히 구성 파일이 작동하는 방식에 대해 이해하지 못했습니다.

Google에서 검색 할 때마다 web.config에 대한 결과가 표시되지만 Windows Forms 애플리케이션을 작성하고 있습니다.

System.Configuration 네임 스페이스를 사용해야한다는 것을 알아 냈지만 설명서가 도움이되지 않습니다.

내 구성 파일이 XYZ.xml임을 어떻게 정의합니까? 아니면 구성 파일의 "기본"이름이 있습니까? 인식하지 못했습니다.

또한 새 섹션을 어떻게 정의합니까? ConfigurationSection에서 상속하는 클래스를 만들어야합니까?

다음과 같은 값을 가진 구성 파일을 갖고 싶습니다.

<MyCustomValue>1</MyCustomValue>
<MyCustomPath>C:\Some\Path\Here</MyCustomPath>

간단한 방법이 있습니까? 간단한 구성 파일을 읽고 쓰는 방법을 간단한 방법으로 설명 할 수 있습니까?


App.Config를 사용하려고합니다.

프로젝트에 새 항목을 추가하면 애플리케이션 구성 파일이라는 것이 있습니다. 그것을 추가하십시오.

그런 다음 구성 / 앱 설정 섹션에 키를 추가합니다.

처럼:

<configuration>
 <appSettings>
  <add key="MyKey" value="false"/>

다음을 수행하여 회원 액세스

System.Configuration.ConfigurationSettings.AppSettings["MyKey"];

이것은 .net 2 이상에서 작동합니다.


이전 답변에 대한 설명 ...

1) 프로젝트에 새 파일 추가 (추가-> 새 항목-> 응용 프로그램 구성 파일)

2) 새 구성 파일이 솔루션 탐색기에 App.Config로 나타납니다.

3) 다음을 템플릿으로 사용하여이 파일에 설정을 추가합니다.

<configuration>
  <appSettings>
    <add key="setting1" value="key"/>
  </appSettings>
  <connectionStrings>
    <add name="prod" connectionString="YourConnectionString"/>
  </connectionStrings>
</configuration>

4) 다음과 같이 검색하십시오.

private void Form1_Load(object sender, EventArgs e)
{
    string setting = ConfigurationManager.AppSettings["setting1"];
    string conn = ConfigurationManager.ConnectionStrings["prod"].ConnectionString;
}

5) 빌드되면 출력 폴더에 <assemblyname> .exe.config라는 파일이 포함됩니다. 이것은 App.Config 파일의 복사본입니다. 이 파일을 만들기 위해 개발자가 추가 작업을 수행 할 필요가 없습니다.


이전 답변을 빠르게 읽어 보면 정확 해 보이지만 VS 2008의 새로운 구성 기능을 언급 한 사람이없는 것 같습니다. 여전히 app.config (컴파일시 YourAppName.exe.config에 복사 됨)를 사용하지만 속성을 설정하고 유형을 지정하는 UI 위젯이 있습니다. 프로젝트의 "Properties"폴더에서 Settings.settings를 두 번 클릭합니다.

가장 좋은 점은 코드에서이 속성에 액세스하는 것이 형식 안전하다는 것입니다. 컴파일러는 속성 이름을 잘못 입력하는 것과 같은 명백한 실수를 포착합니다. 예를 들어 app.config의 MyConnectionString이라는 속성은 다음과 같이 액세스됩니다.

string s = Properties.Settings.Default.MyConnectionString;

App.config 파일 (web.config와 매우 유사)을 만들어야합니다.

프로젝트를 마우스 오른쪽 버튼으로 클릭하고 새 항목, 새 "응용 프로그램 구성 파일"을 추가해야합니다.

System.Configuration을 사용하여 프로젝트에 추가했는지 확인하십시오.

Then you can add values to it

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <appSettings>
    <add key="setting1" value="key"/>
  </appSettings>
  <connectionStrings>
    <add name="prod" connectionString="YourConnectionString"/>
  </connectionStrings>
</configuration>

    private void Form1_Load(object sender, EventArgs e)
    {
        string setting = ConfigurationManager.AppSettings["setting1"];
        string conn = ConfigurationManager.ConnectionStrings["prod"].ConnectionString;
    }

Just a note, according to Microsoft, you should use ConfigurationManager instead of ConfigurationSettings. (see the remarks section) "The ConfigurationSettings class provides backward compatibility only. For new applications you should use the ConfigurationManager class or WebConfigurationManager class instead. "


The default name for a configuration file is [yourexe].exe.config. So notepad.exe will have a configuration file named notepad.exe.config, in the same folder as the program. This is a general configuration file for all aspects of the CLR and Framework, but can contain your own settings under an <appSettings> node.

The <appSettings> element creates a collection of name-value pairs which can be accessed as System.Configuration.ConfigurationSettings.AppSettings. There is no way to save changes back to the configuration file, however.

It is also possible to add your own custom elements to a configuration file - for example, to define a structured setting - by creating a class that implements IConfigurationSectionHandler and adding it to the <configSections> element of the configuration file. You can then access it by calling ConfigurationSettings.GetConfig.

.NET 2.0 adds a new class, System.Configuration.ConfigurationManager, which supports multiple files, with per-user overrides of per-system data. It also supports saving modified configurations back to settings files.

Visual Studio creates a file called App.config, which it copies to the EXE folder, with the correct name, when the project is built.


The best ( IMHO ) article about .NET Application configuration is on CodeProject Unraveling the Mysteries of .NET 2.0 Configuration. And my next favorite (shorter) article about sections in .net configuration files is Understanding Section Handlers - App.config File.


In Windows forms, you have an app.config, which is very similar to web.config. But since what I see you need it for are custom values, I suggest using Settings. To do that, open your project properties, then go to settings. If a settings file does not exist you will have a link to create one. Then, you can add the settings to the table you see there, which would generate both the appropriate XML, and a Settings class that can be used to load and save the settings. The settings class will be named something like DefaultNamespace.Properties.Settings. Then, you can use code similar to:

using DefaultNamespace.Properties;

namespace DefaultNamespace {
    class Class {
        public int LoadMySettingValue() {
            return Settings.Default.MySettingValue;
        }
        public void SaveMySettingValue(int value) {
            Settings.Default.MySettingValue = value;
        }
    }
}

I agree with the other answers that point you to app.config. However, rather than reading values directly from app.config, you should create a utility class (AppSettings is the name I use) to read them and expose them as properties. The AppSettings class can be used to aggregate settings from several stores, such as values from app.config and application version info from the assembly (AssemblyVersion and AssemblyFileVersion).


A very simple way of doing this is to use your your own custom Settings class.


System.Configuration.ConfigurationSettings.AppSettings["MyKey"];

AppSettings has been deprecated and is now considered obsolete. [ link ]

In addition the appSettings section of the app.config has been replaced by the applicationSettings section.

As someone else mentioned, you should be using System.Configuration.ConfigurationManager [ link ] which is new for .Net 2.0


What version of .Net and VS are you using?

When you created the new project, you should have a file in your solution called app.config, that is the default configuration file.

참고URL : https://stackoverflow.com/questions/114527/simplest-way-to-have-a-configuration-file-in-a-windows-forms-c-sharp-application

반응형