关于控制台应用程序:C#将配置文件嵌入exe

c# embed config file within exe

我有一个控制台程序" A",它在给定的位置将运行程序" B"和程序" C"。但是我在与每个程序关联的app.config中遇到问题。基本上,程序A只是一个包装类,它调用不同的控制台应用程序,它不应具有任何app.config,但应使用当前正在运行的程序的app config。因此,从理论上讲,程序B应该只有2个app.config,而程序C应该只有2个。

因此,如果我们运行程序A并执行了程序B,则应使用程序B的app.config获取信息,而当程序C执行后,则应使用程序C的app.config。

有没有办法做到这一点?目前我正在这样做:

1
var value =  ConfigurationManager.OpenExeConfiguration(Assembly.GetExecutingAssembly().Location).AppSettings.Settings["ProgramBKey"].Value;

它似乎不起作用。我在Assembly.GetExecutingAssembly().Location上检查了调试,它的变量是 bin Debug ProgramB.exe和'ConfigurationManager.OpenExeConfiguration(Assembly.GetExecutingAssembly()。Location).AppSettings'在有键值时设置为Count = 0下面。

示例程序A:

1
2
3
4
5
6
7
static void Main(string[] args)
{
    if(caseB)
        B.Program.Main(args)
    else if(caseC)
        C.Program.Main(args)
}

程序B的示例app.config:

1
2
3
4
5
6
7
8
9
<?xml version="1.0"?>
<configuration>
   
   
  </appSettings>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0" />
  </startup>
</configuration>


编辑:以下答案与原始帖子中的此问题有关:"是否可以在程序的exe中为B和C编译app.config。"

您可以使用"嵌入式资源"功能。这是一个使用XML文件作为嵌入资源的小示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
public static class Config
{
    static Config()
    {
        var doc = new XmlDocument();
        using (var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("Fully.Qualified.Name.Config.xml"))
        {
            if (stream == null)
            {
                throw new EndOfStreamException("Failed to read Fully.Qualified.Name.Config.xml from the assembly's embedded resources.");
            }

            using (var reader = new StreamReader(stream))
            {
                doc.LoadXml(reader.ReadToEnd());
            }
        }

        XmlElement aValue = null;
        XmlElement anotherValue = null;

        var config = doc["config"];
        if (config != null)
        {
            aValue = config["a-value"];
            anotherValue = config["another-value"];
        }

        if (aValue == null || anotheValue == null)
        {
            throw new XmlException("Failed to parse Config.xml XmlDocument.");
        }

        AValueProperty = aValue.InnerText;
        AnotherValueProperty = anotherValue.InnerText;
    }
}


您可以使用同一配置文件拥有多个应用程序。这样,当您切换应用程序时,它们都可以找到自己的配置文件部分。

我通常的做法是...首先让每个应用程序"做自己的事",然后将配置文件A的相关部分复制到配置文件B中。

它看起来像这样:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<configSections>
    <sectionGroup>
         <sectionGroup name="applicationSettings"...A>
         <sectionGroup name="userSettings"...A>
         <sectionGroup name="applicationSettings"...B>
         <sectionGroup name="userSettings"...B>


    <A.Properties.Settings>
    <B.Properties.Settings>

<userSettings>
    <A.Properties.Settings>
    <B.Properties.Settings>


对我来说,整件事听起来像是一个"设计问题"。为什么要使用程序A的配置打开程序B?

您是所有这些程序的作者吗?您可能要改用dll文件。这将为您省去麻烦,因为所有代码都在运行Programm的配置下运行。