简体   繁体   中英

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

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:

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#.

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.

<?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>
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 ConfigurationSection and use:

ConfigurationManager.GetSection()

用这个 :

System.Configuration.ConfigurationManager.AppSettings[""]

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).

 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM