5

私は次のようにアセンブリの構成にアクセスしています:

ExeConfigurationFileMap map = new ExeConfigurationFileMap();
map.ExeConfigFilename = Assembly.GetExecutingAssembly().Location + ".config";
Configuration conf = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None);
AppSettingsSection appSettings = conf.AppSettings;

私の.configファイルには次のようなセクションが含まれています

<configSections>
    <sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
        <section name="CsDll.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
    </sectionGroup>
</configSections>
<connectionStrings>
    <add name="CsDll.Properties.Settings.SabreCAD" connectionString="A Connection string." />
    <add name="CsDll.Properties.Settings.StpParts" connectionString="Another connection string" />
</connectionStrings>
 <applicationSettings>
        <CsDll.Properties.Settings>
            <setting name="StpInsertSearchPath" serializeAs="Xml">
                <value>
                    <ArrayOfString xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                        xmlns:xsd="http://www.w3.org/2001/XMLSchema">
                        <string>A string</string>
                        <string>Another string in the collection</string>

.configファイルを編集すると、変更を含む接続文字列を正常に読み取ることができます。だから、私は正しいファイルに接続していることを知っています。しかし、appSettingsオブジェクト内にその文字列コレクションが見つかりません。.SettingsKeyValueConfigurationCollectionにはありません。文字列コレクションはどこにありますか?

4

4 に答える 4

6

この単純な構文を使用して、コレクション内のアイテムにアクセスする必要があります

foreach (string s in CsDll.Properties.Settings.Default.StpInsertSearchPath)
{
    Console.WriteLine(s);
}

編集:

次のコードはトリックを行う必要があります

ExeConfigurationFileMap map = new ExeConfigurationFileMap(); 
map.ExeConfigFilename = Assembly.GetExecutingAssembly().Location + ".config"; 
Configuration conf = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None); 
ConfigurationSectionGroup appSettingsGroup = conf.GetSectionGroup("applicationSettings");
ClientSettingsSection clientSettings = (ClientSettingsSection) appSettingsGroup.Sections["CsDll.Properties.Settings"];
ConfigurationElement element = clientSettings.Settings.Get("StpInsertSearchPath");
string xml = ((SettingElement)element).Value.ValueXml.InnerXml;
XmlSerializer xs = new XmlSerializer(typeof(string[]));
string[] strings = (string[])xs.Deserialize(new XmlTextReader(xml, XmlNodeType.Element, null));
foreach (string s in strings)
{
    Console.WriteLine(s);
}

もっと短い方法があるかもしれませんが、これは私にとってはうまくいきます。

于 2009-08-05T21:28:57.717 に答える
3

設定から抽出しようとしているStringCollectionの場合

var strings = (StringCollection) Properties.Settings.Default["StpInsertSearchPath"];

XmlSerializerを必要とせずに同じくらい達成します

于 2012-05-23T13:01:21.640 に答える
2

AppSettingsとConnectionStringsはどちらも、ConfigurationManagerで直接使用できるプロパティです。

ただし、VS設定デザイナで編集できる 使い慣れた Settings.settingsに対応するapplicationSettingsuserSettingsは、簡単に取得することはできません。AppSettingsは、使用中の構成ファイルのまったく異なるセクションにあるapplicationSettingsと同じではありません。

applicationSettingsuserSettingsを取得するには、上記のマイニングアプローチまたはバリアントを使用する必要があります。また、applicationSettingsは、実行時にまったく書き込みができない場合にのみ、アプリケーションを次に起動したときに更新されます。

例(他の場所からの引用-ありがとう):

public static string ReadSetting(string sectionGroupName, string sectionName, string settingName, Configuration config = null)
    {
        if (config == null)
            config = SharedConfigSettings;
        // Get sectionGroup
        var sectionGroup =
          config.GetSectionGroup(sectionGroupName);

        // Get section
        var section =
          (ClientSettingsSection)sectionGroup.Sections.Get(sectionName);
        // Get setting
        var setting = section.Settings.Get(settingName);
        // Read setting value
        return setting.Value.ValueXml.InnerText;
    }

そして別の例(多くの例から引用-世界に感謝します):

///<summary>
    /// return the applicationSettings section 
    ///</summary>
    ///<returns></returns>
    public static ClientSettingsSection GetSettingsSection(ConfigurationSectionGroup group, string clientSectionName)
    {
        return (ClientSettingsSection)group.Sections[clientSectionName];
    }


    ///<summary>
    /// return the section settings collection
    ///</summary>
    ///<returns></returns>
    public static System.Configuration.SettingElementCollection GetSettingsCollection(ClientSettingsSection section)
    {
        return section.Settings;
    }

    ///<summary>
    /// return the connectionStrings section collection
    ///</summary>
    ///<returns></returns>
    public static System.Configuration.SettingElementCollection ConnectionStringsCollection()
    {
        return ((ClientSettingsSection)SharedConfigSettings.GetSection("connectionStrings")).Settings;
    }

    ///<summary>
    /// A collection of all the UserSettings in a SettingElementCollection
    ///</summary>
    ///<returns></returns>
    public static SettingElementCollection UserSettings()
    {
        return
            GetSettingsCollection(GetSettingsSection(GetSettingsSectionGroup(@"userSettings"),
                                                     @"MyAssembly.Properties.Settings"));
    }

    ///<summary>
    /// A collection of all the ApplicationSettings in a SettingElementCollection
    ///</summary>
    ///<returns></returns>
    public static SettingElementCollection ApplicationSettings()
    {
        return
            GetSettingsCollection(GetSettingsSection(GetSettingsSectionGroup(@"applicationSettings"),
                                                     @"MyAssembly.Properties.Settings"));
    }

次に、残念ながら、これらのセクションの設定コレクションにあるSettingElementオブジェクトを処理する必要があります。たとえば、applicationSettings SettingElement(実行時に動的に更新できないもの)の文字列でない限り、それぞれをプロパティTypeに逆シリアル化する必要があります。

(エクササイズ)

 var y = GetSettingsSection(GetSettingsSectionGroup(@"applicationSettings"), @"MyAssembly.Properties.Settings");
 var c = (y.Settings.Cast<SettingElement>().FirstOrDefault(s => s.Name == "WellKnownDirectories").Value).ValueXml
                .InnerXml; // the setting as Xml
 var xs = new XmlSerializer(typeof(string[]));
 var strings = (string[])xs.Deserialize(new XmlTextReader(c, XmlNodeType.Element, null));

foreach (string s in strings)
        {
            Console.WriteLine(s);
        }

文字列プロパティの場合は簡単です(この例は、上記の最初の例と本質的に冗長です)。

var s = (y.Settings.Cast<SettingElement>().FirstOrDefault(s => s.Name == "MyUserSettingName").Value).ValueXml
                .InnerText

これらの例はすべて、applicationSettingsをいじっています。同じアプローチでuserSettingsを使用できますが、おそらくいくつかの保存メソッドなどが追加されます。メイン、ローミング、ローカルなど、いくつかの多くの構成ファイルのどれが実際に再生されているかを(多かれ少なかれ)追跡する必要があります。 。

なぜ私はこれをしているのですか?2つの関連するアプリケーションと共通のクラスライブラリ(または複数のライブラリ)はすべて、設定が視覚的に管理されているアプリケーションの1つが所有する同じ設定を使用する必要があるためです。誰かがこれをより良い方法で解決しましたか?

ありがとう。

于 2011-07-21T19:35:22.357 に答える
1

接続文字列は通常、構成マネージャーのConnectionStringsプロパティ内にあります。静的メソッドを使用すると、はるかに簡単な方法でアクセスできるはずです。

string myConnectionString = ConfigurationManager.ConnectionStrings["connectioStringName"];

ConfigurationManagerがAppSettingsプロパティを介してアクセスできるようにするには、.configファイルで「ApplicationSettings」の代わりに「AppSettings」タグを使用する必要があると思います。

ConfigurationManagerがどのように機能するかについては、これで問題が解決するかどうかはわかりませんが、名前を変更してカスタムセクショングループを削除すると、AppSettingsが正しく機能するはずです。

編集 はい、ConfigurationManagerのAppSettingsプロパティが.configファイルで指定されたセクションにアクセスしているようです。

于 2009-08-05T21:26:17.160 に答える