我如何在VS2010 c#控制台应用程序中编译我的App.config ?

时间:2021-11-06 07:28:54

I'm creating a console app in Visual Studio 2010 with c#. I want this app to be stand alone, in that all you need is the exe, and you can run it from anywhere. I also want to use app.config to store connection strings and so on.

我正在用c#在Visual Studio 2010中创建一个控制台应用程序。我希望这个应用程序是独立的,你所需要的就是exe,你可以在任何地方运行它。我还想使用app.config来存储连接字符串等等。

My problem is that I can't seem to figure out how to include that app.config data into the compiled exe. I do see it creates appname.exe.config, but I don't want people to have to worry about grabbing two separate files when they get the app.

我的问题是,我似乎不知道如何将app.config数据包含到编译后的exe中。我确实看到它创建了appname.exe。配置,但我不希望人们在获得应用程序时需要考虑获取两个单独的文件。

None of the googling I've done has come up with anything. Is this even possible?

我在谷歌上搜索过的所有东西都没有找到。这是可能吗?

10 个解决方案

#1


13  

You can't. Half the point of such config files is to allow changes to the configuration of the app outside of the app itself.

你不能。这种配置文件的一半目的是允许在应用程序本身之外更改应用程序的配置。

You would simply have to modify your program so that it didn't have a dependency on the app config file -- easiest way to do that would be to just stick the values inside your config into read only global variables.

你只需要修改你的程序,这样它就不会依赖于app配置文件——最简单的方法就是将配置中的值插入到只读全局变量中。

#2


8  

I can see where you are going with this, but the answer might be a bit more complicated than you were looking for.

我可以看到你的答案,但是答案可能比你想要的要复杂一点。

  1. Make app.config to be an embedded resource.
  2. 将app.config设置为嵌入式资源。
  3. Manually parse the app.config to get default app settings / connection strings / etc
  4. 手动解析app.config以获得默认的app设置/连接字符串/等等
  5. Still look for an app.config and override the defaults you read in earlier with the app.config values
  6. 仍然寻找一个app.config并覆盖您在前面使用app.config值读取的默认值。

This way you have some reasonable defaults that you don't have to maintain separate from you app.config as constants, you can run your app as just an exe, and you can still modify it at runtime by adding back in the app.config.

这样,您就有了一些合理的默认值,您不必将app.config作为常量来维护,您可以将应用程序作为exe运行,并且您仍然可以在运行时通过在app.config中添加来修改它。

The one thing to remember, is that reading in the app.config from a resource won't give you the same behavior as the normal app.config. You are basically reading it in and using it by hand.

需要记住的一点是,从资源读取app.config中的行为与普通的app.config不同。你基本上是在阅读和手工使用它。

#3


5  

You mean you need to add it to the exe as a resource? Well, first of all you cannot, app.config is file based not resource based.

你的意思是你需要把它作为资源添加到exe中?首先,app.config是基于文件而不是基于资源的。

On the other hand, the only point of config file is that you can change it. Otherwise just hard-code or use constants.

另一方面,配置文件的唯一一点是您可以更改它。否则就是硬编码或使用常量。

#4


3  

Generally, you don't want to do this as your app.config provides a mechanism by which configuration may be done at runtime. As far as you specific goal (maintaining configuration outside of your code, but have it follow the binary), you have a couple of options:

通常,您不希望这样做,因为您的app.config提供了一种机制,可以在运行时进行配置。就您的特定目标(维护代码之外的配置,但是要遵循二进制),您有几个选项:

  • Dynamically create a configuration file
  • 动态创建配置文件
  • Store the settings in the registry
  • 将设置存储在注册表中
  • Store the settings as resource strings within the console application
  • 将设置存储为控制台应用程序中的资源字符串

I am sure there are other, more creative, options available. My recommendation would be for the second option. When the application is first launched, create the necessary keys and set their default values from the executable. That way, if you need to do any debugging at a later date, you can simply run regedit and make any necessary changes without recompiling.

我相信还有其他更有创意的选择。我的建议是第二种选择。当应用程序首次启动时,创建必要的键并从可执行文件中设置它们的默认值。这样,如果您需要在以后进行任何调试,您只需运行regedit并进行任何必要的更改,而无需重新编译。

#5


3  

As others have pointed out, the idea behind a configuration file is to avoid hard-coded values.

正如其他人指出的,配置文件背后的思想是避免硬编码的值。

What you might do as an alternative is to to write a custom configuration section, with every element optional and with default values. That way anyone who can get by with the defaults doesn't need a config file. But if they need to override a default, they can provide one.

作为一种替代方法,您可以编写一个自定义配置部分,每个元素都可选,并带有默认值。这样,任何能够通过默认设置的人都不需要配置文件。但是如果他们需要重写默认值,他们可以提供一个。

(Sorry, just a bit of brainstorming. I don't have an example available.)

抱歉,只是头脑风暴。我没有现成的例子。

#6


3  

Like people are saying here the whole point of a config file is for modifying some settings outside the application. You can hard-code or use constants but you can also use the registry in windows if you want. That way you can make changes to the application and still only have a single exe file.

就像人们在这里说的,配置文件的整个要点是修改应用程序之外的一些设置。您可以硬编码或使用常量,但如果需要,也可以在windows中使用注册表。这样,您就可以对应用程序进行更改,并且仍然只有一个exe文件。

The code project has some good info about reading, writing and deleting from the registry. http://www.codeproject.com/KB/system/modifyregistry.aspx But be careful when editing the registry. Alot of applications are depending on it so you could destroy some settings if you do something wrong. I recommend reading and then doing.

代码项目有一些关于从注册表中读取、写入和删除的很好的信息。在编辑注册表时要小心。很多应用程序都依赖于它,所以如果你做错了什么,你可以破坏一些设置。我建议先阅读,然后再做。

public string Read(string KeyName)  {
RegistryKey rk = baseRegistryKey;
// Open a subKey as read-only

RegistryKey sk1 = rk.OpenSubKey(subKey);
// If the RegistrySubKey doesn't exist -> (null)

if ( sk1 == null )
{
    return null;
}
else
{
    try 
    {
        // If the RegistryKey exists I get its value
        // or null is returned.
        return (string)sk1.GetValue(KeyName.ToUpper());
    }
    catch (Exception e)
    {
        // AAAAAAAAAAARGH, an error!
        ShowErrorMessage(e, "Reading registry " + KeyName.ToUpper());
        return null;
    }
  }
}

public bool Write(string KeyName, object Value)  {
  try
  {
      // Setting
      RegistryKey rk = baseRegistryKey ;
      // I have to use CreateSubKey 
      // (create or open it if already exits), 
      // 'cause OpenSubKey open a subKey as read-only
      RegistryKey sk1 = rk.CreateSubKey(subKey);
      // Save the value
      sk1.SetValue(KeyName.ToUpper(), Value);
      return true;
  }
  catch (Exception e) {
        // AAAAAAAAAAARGH, an error!
        ShowErrorMessage(e, "Writing registry " + KeyName.ToUpper());
        return false;
    }
  }    

public bool DeleteKey(string KeyName)  {
  try
  {
      // Setting
      RegistryKey rk = baseRegistryKey ;
      RegistryKey sk1 = rk.CreateSubKey(subKey);
      // If the RegistrySubKey doesn't exists -> (true)
      if ( sk1 == null )
          return true;
      else
          sk1.DeleteValue(KeyName);
      return true;
  }
  catch (Exception e)
  {
      // AAAAAAAAAAARGH, an error!
      ShowErrorMessage(e, "Deleting SubKey " + subKey);
      return false;
  }
}

Of course this would only work on Windows. I assume that you are using Visual Studio so you are probably using Windows.

当然,这只适用于Windows。我假设您正在使用Visual Studio,所以您可能正在使用Windows。

Happy coding and good luck!

快乐的编码和好运!

#7


3  

Best workaround looks like to create it yourself at the application startup.

最好的解决方案是在应用程序启动时自己创建。

  1. Add App.Config as a resource, rename it to "App_Config"
  2. 添加App.Config作为资源,将其重命名为“App_Config”
  3. Check if config file exists
  4. 检查配置文件是否存在
  5. If not, write default .config file
  6. 如果没有,则写入默认的.config文件

Example code:

示例代码:

Program.cs

Program.cs

    [STAThread]
    static void Main()
    {
        CreateConfigIfNotExists();
    }

    private static void CreateConfigIfNotExists()
    {
        string configFile = string.Format("{0}.config", Application.ExecutablePath);

        if (!File.Exists(configFile))
        {
            File.WriteAllText(configFile, Resources.App_Config);
        }
    }

Remember that it will only write your current config when building. It will not update it automatically when you deploy a new version. It will include the config as is when building. But this could be enough :)

记住,它只在构建时编写当前配置。当您部署新版本时,它不会自动更新它。它将包含构建时的配置。但这足够了:)

#8


2  

Please the first answer on this previous post - Configuration File as Embedded Resource

请在此之前的post - Configuration文件作为嵌入式资源的第一个答案。

#9


1  

IL Merge has lot issue with wpf executable also slow. I ended up using Cosura.Fody https://github.com/Fody/Costura and using command line parameter for passing my app config value. Also using iexpress http://en.wikipedia.org/wiki/IExpress to create final executable with command line args and exe merged together

IL合并有很多问题与wpf可执行也很慢。最后我用了Cosura。Fody https://github.com/Fody/Costura并使用命令行参数传递我的app配置值。还可以使用iexpress http://en.wikipedia.org/wiki/IExpress创建最终可执行文件,命令行args和exe合并在一起

#10


-2  

Take a winform application for example, during compilation, a file 'xxx.EXE.config' will be generated along with the output EXE file. It will contain the 'app.config' settings. Distribute this as well.

以winform应用程序为例,在编译期间,使用一个文件'xxx.EXE。配置'将与输出EXE文件一起生成。它将包含“app.config”设置。分发。

#1


13  

You can't. Half the point of such config files is to allow changes to the configuration of the app outside of the app itself.

你不能。这种配置文件的一半目的是允许在应用程序本身之外更改应用程序的配置。

You would simply have to modify your program so that it didn't have a dependency on the app config file -- easiest way to do that would be to just stick the values inside your config into read only global variables.

你只需要修改你的程序,这样它就不会依赖于app配置文件——最简单的方法就是将配置中的值插入到只读全局变量中。

#2


8  

I can see where you are going with this, but the answer might be a bit more complicated than you were looking for.

我可以看到你的答案,但是答案可能比你想要的要复杂一点。

  1. Make app.config to be an embedded resource.
  2. 将app.config设置为嵌入式资源。
  3. Manually parse the app.config to get default app settings / connection strings / etc
  4. 手动解析app.config以获得默认的app设置/连接字符串/等等
  5. Still look for an app.config and override the defaults you read in earlier with the app.config values
  6. 仍然寻找一个app.config并覆盖您在前面使用app.config值读取的默认值。

This way you have some reasonable defaults that you don't have to maintain separate from you app.config as constants, you can run your app as just an exe, and you can still modify it at runtime by adding back in the app.config.

这样,您就有了一些合理的默认值,您不必将app.config作为常量来维护,您可以将应用程序作为exe运行,并且您仍然可以在运行时通过在app.config中添加来修改它。

The one thing to remember, is that reading in the app.config from a resource won't give you the same behavior as the normal app.config. You are basically reading it in and using it by hand.

需要记住的一点是,从资源读取app.config中的行为与普通的app.config不同。你基本上是在阅读和手工使用它。

#3


5  

You mean you need to add it to the exe as a resource? Well, first of all you cannot, app.config is file based not resource based.

你的意思是你需要把它作为资源添加到exe中?首先,app.config是基于文件而不是基于资源的。

On the other hand, the only point of config file is that you can change it. Otherwise just hard-code or use constants.

另一方面,配置文件的唯一一点是您可以更改它。否则就是硬编码或使用常量。

#4


3  

Generally, you don't want to do this as your app.config provides a mechanism by which configuration may be done at runtime. As far as you specific goal (maintaining configuration outside of your code, but have it follow the binary), you have a couple of options:

通常,您不希望这样做,因为您的app.config提供了一种机制,可以在运行时进行配置。就您的特定目标(维护代码之外的配置,但是要遵循二进制),您有几个选项:

  • Dynamically create a configuration file
  • 动态创建配置文件
  • Store the settings in the registry
  • 将设置存储在注册表中
  • Store the settings as resource strings within the console application
  • 将设置存储为控制台应用程序中的资源字符串

I am sure there are other, more creative, options available. My recommendation would be for the second option. When the application is first launched, create the necessary keys and set their default values from the executable. That way, if you need to do any debugging at a later date, you can simply run regedit and make any necessary changes without recompiling.

我相信还有其他更有创意的选择。我的建议是第二种选择。当应用程序首次启动时,创建必要的键并从可执行文件中设置它们的默认值。这样,如果您需要在以后进行任何调试,您只需运行regedit并进行任何必要的更改,而无需重新编译。

#5


3  

As others have pointed out, the idea behind a configuration file is to avoid hard-coded values.

正如其他人指出的,配置文件背后的思想是避免硬编码的值。

What you might do as an alternative is to to write a custom configuration section, with every element optional and with default values. That way anyone who can get by with the defaults doesn't need a config file. But if they need to override a default, they can provide one.

作为一种替代方法,您可以编写一个自定义配置部分,每个元素都可选,并带有默认值。这样,任何能够通过默认设置的人都不需要配置文件。但是如果他们需要重写默认值,他们可以提供一个。

(Sorry, just a bit of brainstorming. I don't have an example available.)

抱歉,只是头脑风暴。我没有现成的例子。

#6


3  

Like people are saying here the whole point of a config file is for modifying some settings outside the application. You can hard-code or use constants but you can also use the registry in windows if you want. That way you can make changes to the application and still only have a single exe file.

就像人们在这里说的,配置文件的整个要点是修改应用程序之外的一些设置。您可以硬编码或使用常量,但如果需要,也可以在windows中使用注册表。这样,您就可以对应用程序进行更改,并且仍然只有一个exe文件。

The code project has some good info about reading, writing and deleting from the registry. http://www.codeproject.com/KB/system/modifyregistry.aspx But be careful when editing the registry. Alot of applications are depending on it so you could destroy some settings if you do something wrong. I recommend reading and then doing.

代码项目有一些关于从注册表中读取、写入和删除的很好的信息。在编辑注册表时要小心。很多应用程序都依赖于它,所以如果你做错了什么,你可以破坏一些设置。我建议先阅读,然后再做。

public string Read(string KeyName)  {
RegistryKey rk = baseRegistryKey;
// Open a subKey as read-only

RegistryKey sk1 = rk.OpenSubKey(subKey);
// If the RegistrySubKey doesn't exist -> (null)

if ( sk1 == null )
{
    return null;
}
else
{
    try 
    {
        // If the RegistryKey exists I get its value
        // or null is returned.
        return (string)sk1.GetValue(KeyName.ToUpper());
    }
    catch (Exception e)
    {
        // AAAAAAAAAAARGH, an error!
        ShowErrorMessage(e, "Reading registry " + KeyName.ToUpper());
        return null;
    }
  }
}

public bool Write(string KeyName, object Value)  {
  try
  {
      // Setting
      RegistryKey rk = baseRegistryKey ;
      // I have to use CreateSubKey 
      // (create or open it if already exits), 
      // 'cause OpenSubKey open a subKey as read-only
      RegistryKey sk1 = rk.CreateSubKey(subKey);
      // Save the value
      sk1.SetValue(KeyName.ToUpper(), Value);
      return true;
  }
  catch (Exception e) {
        // AAAAAAAAAAARGH, an error!
        ShowErrorMessage(e, "Writing registry " + KeyName.ToUpper());
        return false;
    }
  }    

public bool DeleteKey(string KeyName)  {
  try
  {
      // Setting
      RegistryKey rk = baseRegistryKey ;
      RegistryKey sk1 = rk.CreateSubKey(subKey);
      // If the RegistrySubKey doesn't exists -> (true)
      if ( sk1 == null )
          return true;
      else
          sk1.DeleteValue(KeyName);
      return true;
  }
  catch (Exception e)
  {
      // AAAAAAAAAAARGH, an error!
      ShowErrorMessage(e, "Deleting SubKey " + subKey);
      return false;
  }
}

Of course this would only work on Windows. I assume that you are using Visual Studio so you are probably using Windows.

当然,这只适用于Windows。我假设您正在使用Visual Studio,所以您可能正在使用Windows。

Happy coding and good luck!

快乐的编码和好运!

#7


3  

Best workaround looks like to create it yourself at the application startup.

最好的解决方案是在应用程序启动时自己创建。

  1. Add App.Config as a resource, rename it to "App_Config"
  2. 添加App.Config作为资源,将其重命名为“App_Config”
  3. Check if config file exists
  4. 检查配置文件是否存在
  5. If not, write default .config file
  6. 如果没有,则写入默认的.config文件

Example code:

示例代码:

Program.cs

Program.cs

    [STAThread]
    static void Main()
    {
        CreateConfigIfNotExists();
    }

    private static void CreateConfigIfNotExists()
    {
        string configFile = string.Format("{0}.config", Application.ExecutablePath);

        if (!File.Exists(configFile))
        {
            File.WriteAllText(configFile, Resources.App_Config);
        }
    }

Remember that it will only write your current config when building. It will not update it automatically when you deploy a new version. It will include the config as is when building. But this could be enough :)

记住,它只在构建时编写当前配置。当您部署新版本时,它不会自动更新它。它将包含构建时的配置。但这足够了:)

#8


2  

Please the first answer on this previous post - Configuration File as Embedded Resource

请在此之前的post - Configuration文件作为嵌入式资源的第一个答案。

#9


1  

IL Merge has lot issue with wpf executable also slow. I ended up using Cosura.Fody https://github.com/Fody/Costura and using command line parameter for passing my app config value. Also using iexpress http://en.wikipedia.org/wiki/IExpress to create final executable with command line args and exe merged together

IL合并有很多问题与wpf可执行也很慢。最后我用了Cosura。Fody https://github.com/Fody/Costura并使用命令行参数传递我的app配置值。还可以使用iexpress http://en.wikipedia.org/wiki/IExpress创建最终可执行文件,命令行args和exe合并在一起

#10


-2  

Take a winform application for example, during compilation, a file 'xxx.EXE.config' will be generated along with the output EXE file. It will contain the 'app.config' settings. Distribute this as well.

以winform应用程序为例,在编译期间,使用一个文件'xxx.EXE。配置'将与输出EXE文件一起生成。它将包含“app.config”设置。分发。