ConfigStringParser is a tiny library which lets you read and write any configuration values into a connection config string, and convert freely between string and object representations:
config string | ↔ | C# class |
---|---|---|
HostName=example.com; Port=587; EnableSsl=true |
↔ |
public class EmailConfig { public string HostName { get; set;} public int Port { get; set; } public bool EnableSSL { get; set;} } |
You can create a new config string from scratch:
var parser = new ConfigStringParser();
parser.Add({ hostName = "example.com", port = 587, enableSSL = true });
...or start from one you have:
var parser = new ConfigStringParser("HostName=example.com; Port=587; EnableSsl=true");
You can freely add, remove, and overwrite values (keys aren't case sensitive):
parser.Add("UserName", "johnny");
parser["username"] = "billy";
parser.Remove("username");
You can freely map the config string into an object:
EmailConfig config = parser.MapTo<EmailConfig>();
...or fill an existing object:
EmailConfig config = new EmailConfig();
parser.MapTo(config);
You can optionally add data annotations to your class:
[Required]
means the value must be defined. If you try to map a config string without it, you'll get an informativeKeyNotFoundException
.[DisplayName("Other Name")]
provides an alternative name that can appear in the config string. For example, this lets you map a config string likeHost Name=example.com
to a property namedHostName
.
The parser will automatically map most primitive types (including bool
, string
, Guid
, double
, int
, long
, short
, and enums), but doesn't handle dates.
You can check whether a string is equivalent to another one (regardless of order or formatting):
var parser = new ConfigStringParser("HostName=example.com; Port=587; EnableSsl=true");
bool isEqual = parser.IsEquivalentTo("EnableSSL=true; Port=587; HOSTNAME=example.com"); // true