Skip to main content

A simple string token replacement method in C#.

/// <summary>
/// Simple token replacement.
/// </summary>
/// <param name="tokens">
/// The replacement token dictionary. Note that token names are case-sensitive.
/// </param>
/// <param name="content">
/// The content that will be searched and replaced with an appropriate matching token.
/// </param>
/// <returns>A string with matched token keys replaced.</returns>
/// <example>
/// var replacementTokens = new Dictionary&lt;string, string&gt;
/// {
///     { &quot;{Name}&quot;,  &quot;Jon&quot; },
///     { &quot;{Fax}&quot;,   &quot;(999) 999-9999&quot;       },
///     { &quot;{Phone}&quot;, &quot;(888) 888-8888&quot;       }
/// };
/// </example>
public static string ReplaceTokens(Dictionary<string, string> tokens, string content)
{
    foreach (var token in tokens.Keys)
    {
        content = content.Replace(token, tokens[token]);
    }

    return content;
}

//
// Example Usage:
var replacementTokens = new Dictionary<string, string>
{
    { "{Name}", "Jon" },
    { "{Place}", "Some Place" }
};

var content = @"Thank you {Name} for scheduling at {Place}.";

var result = ReplaceTokens(replacementTokens, content);

Console.Write(result);