Ben_G
Ben_G

Reputation: 826

How can I reference an app.config from two separate projects (.csproj files)?

I have two .csproj files in my app that both generate an .exe and both have C# programs that need values from the app.config. So since there can only be one app.config file (they're build into the same folder) I thought I'd just put the values that the second program (let's call it b.cs/b.exe) needs in the app.config of the .csproj of the first program (a.cs/a.exe). But the second program can't seem to access the app.config. It's there and the values are there but when I run string x = ConfigurationManager.AppSettings["BuildVersion"];, x is always empty. If I run the same code from a.exe it works fine. It's as if the app.config has some info imbedded in the .exe file that I'm not able to see or set anywhere.

Any ideas how I can access values in anapp.config from two separate projects?

Upvotes: 0

Views: 1998

Answers (4)

Ben_G
Ben_G

Reputation: 826

Adding as a link worked, but I need to copy the b.exe.config file to the output directory too. I guess that file get's generated in addition to a.exe.config and they're just copies of one another based on the added link.

Upvotes: 0

Jesse Johnson
Jesse Johnson

Reputation: 1718

Have you tried adding as a linked item?

Place the app.config in a common location then right click on each of the projects to select Add -> Existing Item. Select the file and click the arrow on the Add button and choose Add as link.

Share code with Add as Link

Upvotes: 1

Matthew Alltop
Matthew Alltop

Reputation: 545

You can use the file parameter in the app.config appSettings node to point it at the other app's config settings that you need:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
    <startup>
    </startup>
    <appSettings file="C:\MasterConfig.config">
        <add key="applicationMode" value="Dev"/>
        <add key="ServiceInterval" value="02:00:00"/>
    </appSettings>
</configuration>

Then reference the items you need as you would normally.

Upvotes: 0

Haney
Haney

Reputation: 34922

You can leave the app.config in one project, but add it as a linked (virtual) file in the other project. Instructions from here Including content files in .csproj that are outside the project cone

  • Right click on the project in VS.
  • Add -> Existing Item...
  • Find the file.
  • Select it and,
  • Add as a Link (drop down in the Add Button in the dialog).

Upvotes: 3

Related Questions