0

I'm using C# for Windows. Imagine that I have a string like this (which is a POST request data):

?key=123&toke=64323sac&con=1

In a condition, con=1 parameter should be removed from the string and in other one, it should be there. How can I handle it?

Also, what if con come as the first parameter?

I made a program which gets all of the input data from a HTML form and I'll send them using a raw POST request. So I have all of the data but there is a problem. One of the parameters (which values might be vary in each try) should be removed from the POST data string in a condition. I don't want to apply the condition in HTML parsing process and instead, It should be removed after the full string is gotten.

asDca21
  • 161
  • 1
  • 2
  • 9
  • This question is a textbook case of the [xy problem](http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem/66378#66378). You seem to have some unknown problem that involves these strings, but you haven't described the problem in enough detail for anyone to understand what sort of solution would make sense. – Claies Jan 02 '16 at 14:21
  • @Claies I added some details. See if it would help you. – asDca21 Jan 02 '16 at 14:29
  • Related question: http://stackoverflow.com/questions/829080/. – Sergey Vyacheslavovich Brunov Jan 02 '16 at 14:43

3 Answers3

1

It is necessary:

  1. to parse the query string into a collection of keys and values;
  2. to change the appropriate key(s)/value(s) of the collection;
  3. to build the result query string using the changed collection.

The implementation of the proposed solution:

using System.Collections.Specialized;
using System.Web;

<...>

const string InitialQueryString = "?key=123&toke=64323sac&con=1";

// 1. Parsing.
NameValueCollection queryStringValues = HttpUtility.ParseQueryString(InitialQueryString);

// 2. Changing.
// The additional values can be added.
queryStringValues.Add("custom_key", "custom_value");

// The existing values can be removed using their keys.
if (the_condition)
{
    queryStringValues.Remove("con");
}

// 3. Building.
string queryString = queryStringValues.ToString();
0

Use this to remove a param from the string:

string remove = "con";
string sep = "?";
string result = "";
foreach (string p in postString.Replace("?", "").Split("&"))
{
    if (p.Split("=")[0] != remove)
    {
        result += sep + p;
        sep = "&";
    }
}
return result;
Steve Harris
  • 5,014
  • 1
  • 10
  • 25
  • Would it remove con wherever it is? for example as the first parameter or the last one? I'll try your code. – asDca21 Jan 02 '16 at 14:42
0

You can try it via Regex:

Regex.Replace(input, pattern, string.Empty)

so in your example:

String pattern = "&" + parameterName + "([^&]*)"; // where parameterName e.g. = con

(Tried it in Java [the regex expression] - hope it works in C# aswell)

// EDIT: Your "one time there and then the other time not: Just use a boolean as condition =D

Graphican0
  • 167
  • 11