如何从 C# 读取 VB.NET 项目中的“app.config”文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12390585/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 23:06:03  来源:igfitidea点击:

How to Read an "app.config" File in a VB.NET Project from C#

c#vb.netapp-config

提问by Gitahi Ng'ang'a

I have a solution that contains a VB.NET project and a C# project. The VB.NET project is the main one. It references the C# project for user management services. Both connect to the same database. The connection string to this database is stored in the app.config file of the VB.NET project. It also contains other user and application level settings. I am able to read the connection string from the config from inside C# by using the following line of code:

我有一个包含 VB.NET 项目和 C# 项目的解决方案。VB.NET 项目是主要的项目。它引用了用于用户管理服务的 C# 项目。两者都连接到同一个数据库。此数据库的连接字符串存储在 VB.NET 项目的 app.config 文件中。它还包含其他用户和应用程序级别的设置。我可以使用以下代码行从 C# 内部的配置中读取连接字符串:

String connectionString = ConfigurationManager.ConnectionStrings["Kais2012.My.MySettings.ConnectionString"].ConnectionString;

One of the other application level properties contained in the config file is called "TeamId". I have written the following code to read it from C#.

配置文件中包含的其他应用程序级别属性之一称为“TeamId”。我编写了以下代码来从 C# 中读取它。

String teamId = ConfigurationManager.AppSettings["Kais2012.My.MySettings.TeamId"];

This does not work and I can't figure out why. Any help will be appreciated. Thanks.

这不起作用,我不知道为什么。任何帮助将不胜感激。谢谢。

The way it doesn't work is that teamId returns null. Here's content of the app.config file.

它不起作用的方式是 teamId 返回 null。这是 app.config 文件的内容。

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <configSections>
        <sectionGroup name="userSettings" type="System.Configuration.UserSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
            <section name="Kais2012.My.MySettings" type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" allowExeDefinition="MachineToLocalUser" requirePermission="false" />
        </sectionGroup>
        <sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
            <section name="Kais2012.My.MySettings" type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
        </sectionGroup>
    </configSections>
  <startup useLegacyV2RuntimeActivationPolicy="true">
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/>
  </startup>
    <connectionStrings configProtectionProvider="DataProtectionConfigurationProvider">
        <EncryptedData>
            <CipherData>
                <CipherValue>AQAAANCMnd8BFdERjHoAwE/Cl+sBAAAAnnRg1L0cskebQ8b6DT/j0AQAAAACAAAAAAAQZgAAAAEAACAAAADGL7/5UD/77t+gDIMLQ14qVgAVA9qjBwvafuEDlJdYVwAAAAAOgAAAAAIAACAAAAD40OqR3t0UIxD0ipA99JXk24mbdvRuR8Cz6H0PYectmmACAABG2jSkPRAdCw+AbgevlKkdhx9zW/s+ukhIr58LKeEVwmMFwxxATQxa9kQqP2Ooe11FG+AjkwHBKjzKbc8ZFfu4fobbggTLBT4HHGns1HAaXkozUXgNxdR2D1hrAOBJyjmIZhOVLKu2LHnboncRF7/OTd+zuzORsWia/t14H1qkxAVeyoKwqKCCW4yMIcboDSqzuTvZzzU8wFMCOeYBTdr1sgf80LmXMUMq3HdmN6YURu9lGHxZqL4IBvKuoi0S7wCdJ8WuVZN/ZSC73fQuKGXXT2yM/++W110MJCc5h+cmPO6ooAugFgXRgESR5t3DBhHC9ddBQyXSLr3J2AIKyg6xPOsn1mG6p8w5ibcpfDbblToQPo3kVW7D87jq9CsrCX5B4VnLhDO6qIaf5qVBP5eGqBRzYUu6U/+lpcAelg67N2itQPv9+SnEhqmFWJ90wfs8w+Bakk9LATC8IrdaZP77HIgGYyCpMJ5U8BC9DuIB6tO3BD4E9+nc4Mn03D0hxGxidwjr5DM4i9gU8cutO4V/aEWx8oNw/0oDMmsHPMsTXrniFajOgWwKThDCVtojpuW86R0ShedKYtECIvmgIBSefR1NhHcwGAsIWUy0X95hP/921tJzjTAqaMiMGCB9+0/SkpcybGDg1JW5ljxdlgY0Ad8treC4dFWZW7dCIUynEfY+Xg5lOd96q1jhulpQPj9eJbwy/bFA5gcX+UcaUZL3nIhC2jSm41JMRwKtBlsJHGT3ZhQsTQWLZrmmXO+SGMBzyDDbRvNCdZHJvSuyUCH/Qn9mNkrnvcvsPmxQ8aOI/kAAAABN3SIZqA4kCsK5cY1oI+4aT0K6PX3GgGcubKGvSS9ugEjnkZoHdAdenX2q4BpPIXSyqMvVyc15hB1wHmV8vLbG</CipherValue>
            </CipherData>
        </EncryptedData>
    </connectionStrings>
    <system.diagnostics>
        <sources>
            <!-- This section defines the logging configuration for My.Application.Log -->
            <source name="DefaultSource" switchName="DefaultSwitch">
                <listeners>
                    <add name="FileLog"/>
                    <!-- Uncomment the below section to write to the Application Event Log -->
                    <!--<add name="EventLog"/>-->
                </listeners>
            </source>
        </sources>
        <switches>
            <add name="DefaultSwitch" value="Information" />
        </switches>
        <sharedListeners>
            <add name="FileLog"
                 type="Microsoft.VisualBasic.Logging.FileLogTraceListener, Microsoft.VisualBasic, Version=8.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL"
                 initializeData="FileLogWriter"/>
            <!-- Uncomment the below section and replace APPLICATION_NAME with the name of your application to write to the Application Event Log -->
            <!--<add name="EventLog" type="System.Diagnostics.EventLogTraceListener" initializeData="APPLICATION_NAME"/> -->
        </sharedListeners>
    </system.diagnostics>
    <userSettings>
        <Kais2012.My.MySettings>
            <setting name="AutoNavigation" serializeAs="String">
                <value>True</value>
            </setting>
            <setting name="UseOsk" serializeAs="String">
                <value>False</value>
            </setting>
            <setting name="AutoHideOsk" serializeAs="String">
                <value>False</value>
            </setting>
            <setting name="StretchReviewColumns" serializeAs="String">
                <value>True</value>
            </setting>
            <setting name="DiscountSkipped" serializeAs="String">
                <value>True</value>
            </setting>
            <setting name="AutoDelay" serializeAs="String">
                <value>0</value>
            </setting>
            <setting name="MinAutoDelay" serializeAs="String">
                <value>1000</value>
            </setting>
        </Kais2012.My.MySettings>
    </userSettings>
    <applicationSettings>
        <Kais2012.My.MySettings>
            <setting name="DummyColumn" serializeAs="String">
                <value>CreationTime</value>
            </setting>
            <setting name="PublisherDBName" serializeAs="String">
                <value>kais_final</value>
            </setting>
            <setting name="PublicationName" serializeAs="String">
                <value>pbl_kais_WAKHUTU-PC</value>
            </setting>
            <setting name="SubscriptionDBName" serializeAs="String">
                <value>KAISEQ_USER001</value>
            </setting>
            <setting name="SubscriberServerName" serializeAs="String">
                <value>USER001</value>
            </setting>
            <setting name="PublisherServerName" serializeAs="String">
                <value>WAKHUTU-PC</value>
            </setting>
            <setting name="PublisherLogin" serializeAs="String">
                <value>sa</value>
            </setting>
            <setting name="PublisherPassword" serializeAs="String">
                <value>xxxxxx</value>
            </setting>
            <setting name="UploadToServer" serializeAs="String">
                <value>1</value>
            </setting>
            <setting name="IpAddress" serializeAs="String">
                <value>172.23.14.94</value>
            </setting>
            <setting name="DownloadFromServer" serializeAs="String">
                <value>2</value>
            </setting>
            <setting name="UploadAndDownload" serializeAs="String">
                <value>3</value>
            </setting>
            <setting name="SubscriberPassword" serializeAs="String">
                <value>xxxxxx</value>
            </setting>
            <setting name="PublishingSubscriberServerName" serializeAs="String">
                <value>SUP01</value>
            </setting>
            <setting name="PublishingSubscriberLogin" serializeAs="String">
                <value>sa</value>
            </setting>
            <setting name="PublishingSubscriberPassword" serializeAs="String">
                <value>xxxxxx</value>
            </setting>
            <setting name="PublishingSubscriberDBName" serializeAs="String">
                <value>KAISEQ_SUP01</value>
            </setting>
            <setting name="publishingSubscriberPublicationName" serializeAs="String">
                <value>pbl_kais_KAISEQ_SUP01</value>
            </setting>
            <setting name="SubscriberLogin" serializeAs="String">
                <value>sa</value>
            </setting>
            <setting name="TeamId" serializeAs="String">
                <value>2</value>
            </setting>
            <setting name="DevMode" serializeAs="String">
                <value>True</value>
            </setting>
            <setting name="DevUsername" serializeAs="String">
                <value>admin</value>
            </setting>
            <setting name="DevPassword" serializeAs="String">
                <value>admin</value>
            </setting>
        </Kais2012.My.MySettings>
    </applicationSettings>
</configuration>

回答by habakuk

You can mark the settings as public in the C# project ("Access Modifier" in the property pane of settings) and then you can access it from the vb project (don't forget to add the reference).

您可以在C#项目中将设置标记为public(设置属性窗格中的“访问修饰符”),然后您可以从vb项目中访问它(不要忘记添加引用)。

 Dim settings = New ClassLibraryCSharp.Properties.Settings
 dim con = settings.ConnectionString

Edit:Just saw that your question was for the other direction (setting in vb project, read it in c# project). But you can do it also in the other direction.

编辑:刚刚看到您的问题是针对另一个方向的(在 vb 项目中设置,在 c# 项目中阅读)。但是你也可以在另一个方向上做到这一点。

回答by Christopher M.

ConfigurationManager.AppSettings[""]

Refers, specifically, to the the configuration section <appSettings>not to a custom configuration section group named <applicationSettings>. Either move your configuration to the correct section or implement a custom ConfigurationSectionand use:

特别是指配置节,<appSettings>而不是名为 的自定义配置节组<applicationSettings>。将您的配置移动到正确的部分或实现自定义ConfigurationSection并使用:

ConfigurationManager.GetSection()

回答by Karamafrooz

Use this :

用这个 :

System.Configuration.ConfigurationManager.AppSettings[""]