Replace {x} tokens in strings Replace {x} tokens in strings asp.net asp.net

Replace {x} tokens in strings


A simple approach is to use a foreach and a Dictionary with a String.Replace:

var values = new Dictionary<string, string> {    { "{networkid}", "WHEEE!!" }    // etc.};var url = "http://api.example.com/sale?auth_user=xxxxx&auth_pass=xxxxx&networkid={networkid}&category=b2c&country=IT&pageid={pageid}&programid=133&saleid=1&m={master}&optinfo={optinfo}&publisher={publisher}&msisdn={userId}";foreach(var key in values.Keys){    url = url.Replace(key,values[key]);}


There is no standard way to "replace with dictionary values" in .NET. While there are a number of template engines, it's not very hard to write a small solution for such an operation. Here is an example which runs in LINQPad and utilizes a Regular Expression with a Match Evaluator.

As the result is a URL,it is the callers responsibility to make sure all the supplied values are correctly encoded. I recommend using Uri.EscapeDataString as appropriate .. but make sure to not double-encode, if it is processed elsewhere.

Additionally, the rules of what to do when no replacement is found should be tailored to need. If not-found replacements should be eliminated entirely along with the query string key, the following can expand the regular expression to @"\w+=({\w+})" to also capture the parameter key in this specific template situation.

string ReplaceUsingDictionary (string src, IDictionary<string, object> replacements) {    return Regex.Replace(src, @"{(\w+)}", (m) => {        object replacement;        var key = m.Groups[1].Value;        if (replacements.TryGetValue(key, out replacement)) {            return Convert.ToString(replacement);        } else {            return m.Groups[0].Value;        }    });}void Main(){    var replacements = new Dictionary<string, object> {        { "networkid", "WHEEE!!" }        // etc.    };    var src = "http://api.example.com/sale?auth_user=xxxxx&auth_pass=xxxxx&networkid={networkid}&category=b2c&country=IT&pageid={pageid}&programid=133&saleid=1&m={master}&optinfo={optinfo}&publisher={publisher}&msisdn={userId}";    var res = ReplaceUsingDictionary(src, replacements);    // -> "http://api.example.com/sale?..&networkid=WHEEE!!&..&pageid={pageid}&..    res.Dump();}

More advanced techniques, like reflection and transforms, are possible - but those should be left for the real template engines.


I am guessing you are trying to replace parameters in url with your values. This can be done using C# HttpUtility.ParseQueryString

Get the CurrentURL from

   var _myUrl = System.Web.HttpUtility.ParseQueryString(Request.RawUrl);

Read Parameter from your Query string

   string value1 = _myUrl ["networkid"];

Write a value into the QueryString object.

  _myUrl ["networkid"] = "Your Value";

and then finally turn it back into URL

  var _yourURIBuilder= new UriBuilder(_myUrl ); _myUrl = _yourURIBuilder.ToString();