WinForms应用:将用户输入的API Key保存至config.json的实现咨询
WinForms 保存API Key到config.json实现思路
实现步骤
定义配置实体类
创建与config.json结构匹配的实体类,简化JSON序列化/反序列化操作:public class AppConfig { public string apikey { get; set; } public string steam64id { get; set; } }读取现有配置
编写方法读取config.json,文件不存在时返回空配置对象:private AppConfig LoadConfig() { string configPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "config.json"); if (!File.Exists(configPath)) { return new AppConfig(); } string jsonContent = File.ReadAllText(configPath); return JsonSerializer.Deserialize<AppConfig>(jsonContent); }需引用
System.Text.Json;若使用Newtonsoft.Json,替换为JsonConvert.DeserializeObject<AppConfig>(jsonContent)保存API Key
在保存按钮的点击事件中,更新配置并写入文件:private void btnSave_Click(object sender, EventArgs e) { AppConfig config = LoadConfig(); // 获取TextBox输入并去除首尾空格 config.apikey = txtApiKey.Text.Trim(); // 格式化JSON输出,方便阅读 string jsonContent = JsonSerializer.Serialize(config, new JsonSerializerOptions { WriteIndented = true }); string configPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "config.json"); File.WriteAllText(configPath, jsonContent); MessageBox.Show("API Key已保存"); }
注意事项
- 确保程序拥有当前目录的写入权限,避免保存失败
- 可添加输入验证(如非空检查),防止无效内容写入配置文件
- 若使用Newtonsoft.Json,序列化方法替换为
JsonConvert.SerializeObject(config, Formatting.Indented)
内容的提问来源于stack exchange,提问作者user23231290
相关产品推荐
相关产品推荐

