How to create a text file template?

Asked

Viewed 66 times

1

How do I use an extension file template txt, in such a way that my program can read this template, replace specific points of it and generate an output, for example, in another file txt. For example:

Arquivo_template.txt

Propriedade1: {aqui será substituído pela variável_1}
Propriedade2: {aqui será substituído pela variável_2}
...

Is it possible to use this template scheme? Or I have to generate the file manually?

2 answers

1

Ideally, you should establish a convention for the texts that should be replaced, with some symbol or punctuation type for the variables in your file. For example, :{}

The following function can be useful to perform the function:

    using System.Text.RegularExpressions;

    public static string TrocarTokens(string template, Dictionary<string, string> dicionarioVariaveis)
    {
        var rex = new Regex(@"\:{([^}]+)}");
        return(rex.Replace(template, delegate(Match m)
        {
            string key = m.Groups[1].Value;
            string rep = dicionarioVariaveis.ContainsKey(key)? dicionarioVariaveis[key] : m.Value;
            return(rep);
        }));
    }

Adapted template:

Propriedade1: :{variavel_1}
Propriedade2: :{variavel_2}
...

Use:

var dicionarioValores = new Dictionary<string, string>();
dicionarioValores["variavel_1"] = "Valor 1";
dicionarioValores["variavel_2"] = "Valor 2";
var saida = TrocarTokens(stringDoArquivo, dicionarioValores);

I got the idea from here.

  • Cool, but this way I would always have to read all the lines of the template file to replace it in a gigantic string, right? I wouldn’t have anything like it except I’m a native of the#?

  • Native I don’t know, but I don’t think.

1


Browser other questions tagged

You are not signed in. Login or sign up in order to post.