2

I'm using YamlDotNet Nuget-package to read and write a Yaml file in C#/.Net Framework. While writing yaml file, it creates 3 dots at end of file. Since these dots are optional so I don't want them. Is there a way to exclude them while creating yaml file? This is my code.

   using YamlDotNet.RepresentationModel;

        var input = new StreamReader(Constants.YamlFilePath);
        var yaml = new YamlStream(); 
        yaml.Load(input);
        input.Dispose();
        var config = ((YamlMappingNode)yaml.Documents[0].RootNode).Children["Configuration"];
        ((YamlMappingNode)yaml.Documents[0].RootNode).Children["Configuration"] = new YamlMappingNode
        {
            { "A1", data.A1 },
            { "A2", data.A2 },
            { "A3", data.A3 },
            { "A4", config["A4"].ToString() },
            { "A5", config["A5"].ToString() }
        };

        using (StreamWriter writer = new StreamWriter(Constants.YamlFilePath, false))
            yaml.Save(writer);
Sabir H.
  • 21
  • 2

2 Answers2

2

Currently YamlStream always emits an explicit DocumentEnd event, which is why the dots are written. You can't change that behaviour, but you can write your own IEmitter to force the DocumentEnd event to be implicit:

public class NoDotsEmitter : IEmitter
{
    private readonly IEmitter inner;

    public NoDotsEmitter(IEmitter inner)
    {
        this.inner = inner;
    }

    public void Emit(ParsingEvent @event)
    {
        if (@event is DocumentEnd documentEnd)
        {
            inner.Emit(new DocumentEnd(true));
        }
        else
        {
            inner.Emit(@event);
        }
    }
}

You can then pass an instance of this class to the Save method:

var emitter = new NoDotsEmitter(new Emitter(writer));
yaml.Save(emitter, false);

You can see a working example here: https://dotnetfiddle.net/2yCM2K

Antoine Aubry
  • 12,203
  • 10
  • 45
  • 74
0

You could create a memory stream, do your write, then write the bytes in the memory stream to the file.

Alternatively, you could create a stream writer that writes all the bytes except the last 3 at each call to write.

Tarik
  • 10,810
  • 2
  • 26
  • 40