How to create a text file template?

1

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

File_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 schema? Or do I have to generate the file manually?

    
asked by anonymous 30.08.2016 / 20:40

2 answers

1

Natively you only have String.Replace and RegEx.Replace , even.

I suggest using a ready package like StringTokenFormatter or NamingFormatter , or even a engine , such as RazorEngine .

    
31.08.2016 / 09:30
1

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

The following function may be useful for running 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);
        }));
    }

Template adapted:

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

Usage:

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 .

    
30.08.2016 / 20:49