How to write data to yaml file

Viewed 2380

I'm trying to build a simple windows form that is supposed to write values to yaml configuration file.After being published, the exe file is saved in the config directory.

private void buttonSaveSettings_Click(object sender, EventArgs e)
{
    string hostname = hostnameBox.Text;

    var path = "C:\\Users\\Nick\\Desktop\\packages\\doctrine.yaml";
    var deserializer = new YamlDotNet.Serialization.Deserializer();

    try
    {
        using (var reader = new StreamReader(path))
        {
            var obj = deserializer.Deserialize<Dictionary<object, object>>(reader);
            var doctrine = (Dictionary<object, object>)obj["doctrine"];
            var dbal = (Dictionary<object, object>)doctrine["dbal"];
            var connections = (Dictionary<object, object>)dbal["connections"];
            var dict = (Dictionary<object, object>)connections["default"];

            // TODO: Modify the dictionary
            // dict["dbname"] = "test";

            dict["dbname"] = "test";

            using (StreamWriter writer = new StreamWriter(path))
            {
                // Save Changes
                var serializer = new YamlDotNet.Serialization.Serializer();
                serializer.Serialize(writer, obj);
            }
        }
    }
    catch (Exception exception)
    {
        dumpBox.Text = exception.Message;
    }
}

That's the doctrine config file (packages/doctrine.yaml)

doctrine:
    dbal:
        default_connection: default
        connections:
            default:
                dbname: dbname
                user: user
                password: password
                host: host
                driver: pdo_mysql
                server_version: '10.0.38-MariaDB'

        # IMPORTANT: You MUST configure your server version,
        # either here or in the DATABASE_URL env var (see .env file)
        #server_version: '5.7'
    orm:
        auto_generate_proxy_classes: true
        naming_strategy: doctrine.orm.naming_strategy.underscore_number_aware
        auto_mapping: true
        mappings:
            App:
                is_bundle: false
                type: annotation
                dir: '%kernel.project_dir%/src/Entity'
                prefix: 'App\Entity'
                alias: App

I'm not sure if that task could be handled just by using the System.IO, since we may need some additional parser.

The question is, how can I rewrite each key's value that belongs to doctrine/dbal/connections/default?

2 Answers

You can do the following:

  • First install YamlDotNet (if you use .NET Core dotnet add package YamlDotNet --version 8.1.2) or (if you use the package manager PM> Install-Package YamlDotNet -Version 8.1.2)

Adapt the code for your needs

var path = "/path/to/file.yaml";
var deserializer = new YamlDotNet.Serialization.Deserializer();

try {
    using var reader = new StreamReader(path);
    var obj = deserializer.Deserialize<Dictionary<object, object>>(reader);
    var doctrine = (Dictionary<object, object>)obj["doctrine"];
    var dbal = (Dictionary<object, object>)doctrine["dbal"];
    var connections = (Dictionary<object, object>)dbal["connections"];
    var dict = (Dictionary<object, object>)connections["default"];
    reader.Close()

    // TODO: Modify the dictionary
    // dict["dbname"] = "test";                    

    using var writer = new StreamWriter(path);
    // Save Changes
    var serializer = new YamlDotNet.Serialization.Serializer();
    serializer.Serialize(writer, obj);
} catch (Exception e) {
    // TODO: manage
}  

There is already a Yaml Library for .NET project.

YamlParser parser = new YamlParser();
TextInput input = new TextInput(File.ReadAllText(yamlFilePath));
bool success;
YamlStream yamlStream = parser.ParseYamlStream(input, out success);
if (success)
{
    foreach (YamlDocument doc in yamlStream.Documents)
    {
        // access DataItem by doc.Root
    }
}
else
{
    MessageBox.Show(parser.GetEorrorMessages());
}

Or:

YamlStream yamlStream = YamlParser.Load(yamlFilePath);

Incase of any other help please follow http://yaml-net-parser.sourceforge.net/

You can see this fiddle link https://dotnetfiddle.net/rrR2Bb

Related