NameValueSectionHandler 유형의 ConfigurationSection 값을 가져 오는 방법
저는 C #, Framework 3.5 (VS 2008)로 작업하고 있습니다.
를 사용하여 ConfigurationManager
구성 (기본 app.config 파일이 아님)을 구성 개체에로드합니다.
Configuration 클래스를 사용하여를 얻을 수 ConfigurationSection
있었지만 해당 섹션의 값을 얻는 방법을 찾을 수 없었습니다.
구성에서은 ConfigurationSection
유형 System.Configuration.NameValueSectionHandler
입니다.
그만한 가치 GetSection
는 ConfigurationManager
(기본 app.config 파일에있을 때만 작동) 메서드 를 사용 했을 때 키-값 쌍의 컬렉션으로 캐스팅 할 수있는 객체 유형을 받았으며 방금 수신했습니다. 사전과 같은 값. ConfigurationSection
그러나 Configuration 클래스에서 클래스를 받았을 때 그러한 캐스트를 할 수 없었 습니다.
편집 : 구성 파일의 예 :
<configuration>
<configSections>
<section name="MyParams"
type="System.Configuration.NameValueSectionHandler" />
</configSections>
<MyParams>
<add key="FirstParam" value="One"/>
<add key="SecondParam" value="Two"/>
</MyParams>
</configuration>
app.config에있을 때 사용할 수 있었던 방법의 예 ( "GetSection"메서드는 기본 app.config에만 해당) :
NameValueCollection myParamsCollection =
(NameValueCollection)ConfigurationManager.GetSection("MyParams");
Console.WriteLine(myParamsCollection["FirstParam"]);
Console.WriteLine(myParamsCollection["SecondParam"]);
정확한 문제로 고생했습니다. .config 파일의 NameValueSectionHandler로 인해 문제가 발생했습니다. 대신 AppSettingsSection을 사용해야합니다.
<configuration>
<configSections>
<section name="DEV" type="System.Configuration.AppSettingsSection" />
<section name="TEST" type="System.Configuration.AppSettingsSection" />
</configSections>
<TEST>
<add key="key" value="value1" />
</TEST>
<DEV>
<add key="key" value="value2" />
</DEV>
</configuration>
그런 다음 C # 코드에서 :
AppSettingsSection section = (AppSettingsSection)ConfigurationManager.GetSection("TEST");
btw NameValueSectionHandler는 2.0에서 더 이상 지원되지 않습니다.
여기 쇼가 어떻게 그것을 할 수있는 좋은 게시물.
app.config가 아닌 파일에서 값을 읽으려면 ConfigurationManager로로드해야합니다.
이 방법을 시도하십시오. ConfigurationManager.OpenMappedExeConfiguration ()
MSDN 기사에 사용 방법에 대한 예가 있습니다.
사용해보십시오 AppSettingsSection
대신의 NameValueCollection
. 이 같은:
var section = (AppSettingsSection)config.GetSection(sectionName);
string results = section.Settings[key].Value;
이 작업을 수행 할 수있는 유일한 방법은 섹션 핸들러 유형을 수동으로 인스턴스화하고 원시 XML을 여기에 전달하고 결과 객체를 캐스팅하는 것입니다.
꽤 비효율적 인 것 같지만 거기에 있습니다.
이것을 캡슐화하는 확장 메서드를 작성했습니다.
public static class ConfigurationSectionExtensions
{
public static T GetAs<T>(this ConfigurationSection section)
{
var sectionInformation = section.SectionInformation;
var sectionHandlerType = Type.GetType(sectionInformation.Type);
if (sectionHandlerType == null)
{
throw new InvalidOperationException(string.Format("Unable to find section handler type '{0}'.", sectionInformation.Type));
}
IConfigurationSectionHandler sectionHandler;
try
{
sectionHandler = (IConfigurationSectionHandler)Activator.CreateInstance(sectionHandlerType);
}
catch (InvalidCastException ex)
{
throw new InvalidOperationException(string.Format("Section handler type '{0}' does not implement IConfigurationSectionHandler.", sectionInformation.Type), ex);
}
var rawXml = sectionInformation.GetRawXml();
if (rawXml == null)
{
return default(T);
}
var xmlDocument = new XmlDocument();
xmlDocument.LoadXml(rawXml);
return (T)sectionHandler.Create(null, null, xmlDocument.DocumentElement);
}
}
귀하의 예제에서 호출하는 방법은 다음과 같습니다.
var map = new ExeConfigurationFileMap
{
ExeConfigFilename = @"c:\\foo.config"
};
var configuration = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None);
var myParamsSection = configuration.GetSection("MyParams");
var myParamsCollection = myParamsSection.GetAs<NameValueCollection>();
이것은 오래된 질문이지만 다음 클래스를 사용하여 작업을 수행합니다. Scott Dorman의 블로그를 기반으로합니다 .
public class NameValueCollectionConfigurationSection : ConfigurationSection
{
private const string COLLECTION_PROP_NAME = "";
public IEnumerable<KeyValuePair<string, string>> GetNameValueItems()
{
foreach ( string key in this.ConfigurationCollection.AllKeys )
{
NameValueConfigurationElement confElement = this.ConfigurationCollection[key];
yield return new KeyValuePair<string, string>
(confElement.Name, confElement.Value);
}
}
[ConfigurationProperty(COLLECTION_PROP_NAME, IsDefaultCollection = true)]
protected NameValueConfigurationCollection ConfCollection
{
get
{
return (NameValueConfigurationCollection) base[COLLECTION_PROP_NAME];
}
}
사용법은 간단합니다.
Configuration configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
NameValueCollectionConfigurationSection config =
(NameValueCollectionConfigurationSection) configuration.GetSection("MyParams");
NameValueCollection myParamsCollection = new NameValueCollection();
config.GetNameValueItems().ToList().ForEach(kvp => myParamsCollection.Add(kvp));
다음은 앞서 언급 한이 블로그의 몇 가지 예입니다 .
<configuration>
<Database>
<add key="ConnectionString" value="data source=.;initial catalog=NorthWind;integrated security=SSPI"/>
</Database>
</configuration>
값 얻기 :
NameValueCollection db = (NameValueCollection)ConfigurationSettings.GetConfig("Database");
labelConnection2.Text = db["ConnectionString"];
-
또 다른 예:
<Locations
ImportDirectory="C:\Import\Inbox"
ProcessedDirectory ="C:\Import\Processed"
RejectedDirectory ="C:\Import\Rejected"
/>
가치 얻기 :
Hashtable loc = (Hashtable)ConfigurationSettings.GetConfig("Locations");
labelImport2.Text = loc["ImportDirectory"].ToString();
labelProcessed2.Text = loc["ProcessedDirectory"].ToString();
'development' 카테고리의 다른 글
sun.misc.Unsafe는 어디에 문서화되어 있습니까? (0) | 2020.11.25 |
---|---|
스레드 덤프 분석 도구 / 방법 (0) | 2020.11.25 |
내 heroku 애플리케이션을 자동으로 다시 시작 (0) | 2020.11.25 |
gitignore는 중간에 공백이있는 폴더 내의 파일을 무시합니다. (0) | 2020.11.25 |
보안 페이지의 iframe에있는 안전하지 않은 콘텐츠 (0) | 2020.11.25 |