所以,你有两个部分,以你的问题:
- 你想拥有基于客户端程序中的变量为您的应用程序
- 要自动进行设置更改的过程。
为使自定义设置:
使用AppSettings
。
首先,为System.Configuration
组件添加引用。
在您的app.config文件:
<configuration>
<appSettings>
<add key="ClientID" value="123" />
<add key="ApiUrl" value="http://somesite/TestApp/api.php" />
</appSettings>
</configuration>
在你的代码,阅读设置:
using System;
using System.Configuration;
class Program
{
private static int clientID;
private static string apiUrl;
static void Main(string[] args)
{
// Try to get clientID - example that this is a required field
if (!int.TryParse(ConfigurationManager.AppSettings["ClientID"], out clientID))
throw new Exception("ClientID in appSettings missing or not an number");
// Get apiUrl - example that this isn't a required field; you can
// add string.IsNullOrEmpty() checking as needed
apiUrl = ConfigurationManager.AppSettings["apiUrl"];
Console.WriteLine(clientID);
Console.WriteLine(apiUrl);
Console.ReadKey();
}
}
More about AppSettings on MSDN
要自动设置的创建:
这一切都取决于你想要得到多么复杂。
- 当你建立你的项目,你的
app.config
文件将成为TestApp.exe.config
- 您可以使用
ConfigurationManager
类写配置文件。
- 此外,您可以编写一个小型的Exe文件,它将配置文件写入自定义设置,并将其作为构建操作的一部分执行。很多方法可以实现自动化,这取决于您打算如何部署应用程序。
编程写的app.config文件appSettings部分的一个简单的例子:
public static void CreateOtherAppSettings()
{
Configuration config =
ConfigurationManager.OpenExeConfiguration("OtherApp.config");
config.AppSettings.Settings.Add("ClientID", "456");
config.AppSettings.Settings.Add("ApiUrl", "http://some.other.api/url");
config.Save(ConfigurationSaveMode.Modified);
}
感谢您的快速答复。但是,我怎么实际上可以部署应用程序,因为它是一个独立的.exe,它有可能在exe文件中自动嵌入user.config? – user3280998
你不会将它嵌入到exe文件中 - 它总是一个单独的配置文件。您可以为每个部署生成配置文件,我已经更新了我的答案并正在处理一个示例。 –
@ user3280998:以示例查看更新的答案。这应该足以让你运行它并找出如何最好地生成配置。我不知道你的项目显然更具体,但我已经为你提供了几个选项和例子。 –