如果标题中的询问不正确,我会深表歉意。我不知道该怎么问或要求什么。
--
假设我有一个用C#编写的简单应用程序“ TestApp”。
在该应用程序内部,我有以下变量:
int clientid = 123;
string apiurl = "http://somesite/TestApp/api.php";
当我有一个新客户端时,我需要为他创建一个新的特殊TestApp.exe,更改代码中的“ clientid”变量。
可以自动执行此过程吗?要自动更改该变量并导出exe,而不会干扰我的过程?
--
我之所以这样问,是因为我认为/或者由于下一个受欢迎的例子,我确信这是可能的:
http://download.cnet.com/2701-20_4-1446.html?tag=sideBar;downloadLinks
[它会创建一个特殊的.exe文件,该文件具有预定义的链接,可从此处下载实际文件]
http://torrent2exe.com/
[它将.torrent文件嵌入到特殊的.exe中,只是更改了一些自定义变量,例如torrent名称或下载大小]
再一次,如果我没有正确地问我的问题,并且因为我的英语不好,我会尽力而为,我对此表示歉意。
最佳答案
因此,您的问题分为两部分:
您希望基于您的应用的客户端在程序中包含变量
您要自动执行更改设置的过程。
进行自定义设置:
使用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
类来写入Config文件。此外,您可以编写一个小的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);
}