Muhammad Alkarouri
Muhammad Alkarouri

Reputation: 24672

How to write to the appSettings from an F# console application?

Although it seems lie a simple issue, I am unable to write to a configuration file from an F# console application. My last attempt looks like

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)

I got all sorts of errors. The one corresponding to this code is

System.NullReferenceException: Object reference not set to an instance of an object. at System.Configuration.ConfigurationElement.SetPropertyValue(ConfigurationProperty prop, Object value, Boolean ignoreLocks) ...

There is no good documentation in F# and I find it hard to follow C#/VB documentation. Any suggestions?

Upvotes: 2

Views: 903

Answers (1)

Robert Jeppesen
Robert Jeppesen

Reputation: 7877

You have to check for null and either update or add accordingly.

Something like this:

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
| _         -> ()

Upvotes: 2

Related Questions