【问题标题】:How to write to the appSettings from an F# console application?如何从 F# 控制台应用程序写入 appSettings?
【发布时间】:2012-09-28 17:22:56
【问题描述】:

虽然这似乎是一个简单的问题,但我无法从 F# 控制台应用程序写入配置文件。我的最后一次尝试看起来像

let config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.PerUserRoamingAndLocal)
// config.AppSettings.SectionInformation.AllowExeDefinition <-ConfigurationAllowExeDefinition.MachineToLocalUser
match self.FileName with
| Some name -> config.AppSettings.Settings.["FileName"].Value <- name
| None -> ()
config.Save(ConfigurationSaveMode.Modified)

我遇到了各种各样的错误。这段代码对应的是

System.NullReferenceException:对象引用未设置为对象的实例。 在 System.Configuration.ConfigurationElement.SetPropertyValue(ConfigurationProperty prop, Object value, Boolean ignoreLocks) ...

F# 中没有好的文档,我发现很难遵循 C#/VB 文档。 有什么建议吗?

【问题讨论】:

  • 有问题的KeyValueConfigurationElement 可能根本不存在吗?如果没有,你必须先Settings.Add(key, value)它。
  • 使用Settings.Add时,错误为System.Configuration.ConfigurationErrorsException: An error occurred executing the configuration section handler for appSettings. ---&gt; System.InvalidOperationException: ConfigurationSection properties cannot be edited when locked.
  • 查看 MSDN 上的 this 示例。如果您刚刚创建了一个部分,您可能需要重新加载它,以便其值可供阅读。如果这没有帮助,请考虑在您的问题中添加更多详细信息,以便更容易回答。

标签: f# console-application configurationmanager


【解决方案1】:

您必须检查 null 并相应地更新或添加。

类似这样的:

let config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.PerUserRoamingAndLocal)
let settings = config.AppSettings.Settings
let set (s:KeyValueConfigurationCollection) key value = 
   match s.[key] with 
   | null -> s.Add(key,value)
   | x    -> x.Value <- value
match self.FileName with
| Some name -> set settings "Filename" name
| _         -> ()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-10
    • 1970-01-01
    • 1970-01-01
    • 2017-03-03
    • 1970-01-01
    相关资源
    最近更新 更多