yaml is pretty good way to define config for an application rather than xml file. There are many libraries available for parsing yaml in C#.
Two of the libraries i tried are: yamlconfig and sharpyaml.
I liked the general concept behind yamlconfig but it wasn’t that good to just integrate and get started, so I chose sharpyaml over it.
The thing I liked about sharpyaml is how easy it is to get it going, I did not had much success with yamlconfig.
Also yamlconfig looks far too fancy with Injectors and what not- to just get a simple yaml parsed. Anyway enough ranting.
Lets look at some code.
This is the yaml file I want parsed:
1
2
3
4
5
6
7
8
9
10
|
# mandatory settings
IndexDir: d:\indexdir
LogDir: c:\logs
# these should all be lower-case
FilterPattern:
- pattern1
- pattern2
- pattern3
|
Here is some sample code C# to get this going:
(I am assuming you have added reference to sharpyaml thru nuget)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
|
using SharpYaml.Serialization;
using System.IO;
using System.Text;
class Program
{
private class Config
{
public String IndexDir { get; set; }
public string LogDir { get; set; }
public string[] FilterPattern { get; set; }
public string[] SomeOptionalProp {get; set;}
public override string ToString()
{
var bldr = new StringBuilder();
bldr.AppendLine(string.Format("IndexDir - {0}", IndexDir));
bldr.AppendLine(string.Format("LogDir - {0}", LogDir));
if(FilterPattern != null)
{
bldr.AppendLine(string.Format("FilterPattern:"));
foreach(var fp in FilterPattern)
bldr.AppendLine(string.Format(" - {0}", fp));
}
if(SomeOptionalProp != null)
{
bldr.AppendLine(string.Format("SomeOptionalProp:"));
foreach(var fp in SomeOptionalProp)
bldr.AppendLine(string.Format(" - {0}", fp));
}
return bldr.ToString();
}
}
static void Main(string[] args)
{
var yamlPath = "config.yml";
var input = new StreamReader(yamlPath);
var deserializer = new Serializer();
var config = (Config)deserializer.Deserialize(input, typeof(Config));
Console.WriteLine(config.ToString());
Console.ReadKey();
}
}
|
One of the things is to ensure that your Config
class has to match yaml file. It’s okay to neglect a few properties in yaml, but anything extra on top of your class schema and parsing will fail.
Other than that the code is pretty self-explanatory.
- Lines 7-36: define the
Config
class whose object will contain data from parsed yaml file- think of it as schema for yaml. - Lines 43: create a new
Serializer
object and use it to read yaml from stream (line 41)
Uses reflection internally to populate the fields of your class- see get
and set
for properties are not private.
I have overridden print method on Config
class just to print out what it parsed:
1
2
3
4
5
6
| IndexDir - d:\indexdir
LogDir - c:\logs
FilterPattern:
- pattern1
- pattern2
- pattern3
|
That’s pretty much it..