简体   繁体   English

从流读取的字符串中获取特定值

[英]Get specific value from string read from stream

I have a string that was read from a stream using stream reader. 我有一个使用流阅读器从流中读取的字符串。 This was after a WEB API call and get the response from the request. 这是在调用WEB API之后并从请求中获得响应。 For a cleared view, here is my code. 对于清晰的视图,这是我的代码。

HttpWebRequest request = (HttpWebRequest)WebRequest.Create("SOME URL");
HttpWebResponse response = (HttpWebResponse)request.GetResponse();

Stream resStream = response.GetResponseStream();
StreamReader reader = new StreamReader(resStream);

string s = reader.ReadToEnd();

resStream.Flush();
resStream.Close();
reader.Close();

My string (s) there have a value of "value1=sometring1&value2=somestring2". 我的字符串的值是“ value1 = sometring1&value2 = somestring2”。 I want to get somestring1 and sometring2. 我想获取somestring1和sometring2。 I think there's a better way to do this and not convert the whole stream as a string to get each value. 我认为有一种更好的方法,而不是将整个流转换为字符串以获取每个值。 Do you have any ideas? 你有什么想法? Thanks! 谢谢!

I'd suggest reading into the string and afterwards splitting the data using a method like the following one: 我建议读入字符串,然后使用类似于以下方法的方法拆分数据:

private Dictionary<string, string> SplitValuePairString(string originalString)
{
    Dictionary<string, string> result = new Dictionary<string, string>();

    if (string.IsNullOrEmpty(originalString))
    {
        var keyValuePairs = originalString.Split(new char[] { '&' });

        foreach (string keyValuePair in keyValuePairs)
        {
            var parts = keyValuePair.Split(new char[] { '=' });

            if (parts.Length == 2)
            {
                result.Add(parts[0], parts[1]);
            }
        }
    }

    return result;
}

I think you can parse your string response with a Regex (if it always has this number of parameters, else you will have more results in the MatchCollection ) : 我认为您可以使用Regex解析字符串响应(如果它始终具有此数量的参数,则在MatchCollection中将有更多结果):

MatchCollection results = Regex.Matches(reader.ReadToEnd(), "=([a-z]*[0-9]*)");

string value1 = results[0].Groups[1].Value;
string value2 = results[1].Groups[1].Value;

This code returns exactly from the string "value1=sometring1&value2=somestring2" : 此代码完全从字符串"value1=sometring1&value2=somestring2"

somestring1
somestring2

如果将流转换为string则可以使用System.Web.HttpUtility.ParseQueryString(s)轻松获取somestring1和sometring2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM