How to access collections within NameValueCollection returned by HttpUtility.ParseQueryString?
Using C#, .net 4.0
I'm using HttpUtility.ParseQueryString to parse a mailto URI, as such:
MailMessage message = new MailMessage()开发者_JAVA技巧;
NameValueCollection mailTo = System.Web.HttpUtility.ParseQueryString(mailToUri.OriginalString.Split('?')[1]);
message.Subject = mailTo["subject"];
The URI can have multiple "to" parameters, such as:
mailto://?to=address1@email.com&to=address2@email.com&to=address3@email.com&subject=test&body=this%20should%20be%20the%20body"
When stepping through the code I can see ParseQueryString creates the mailTo["to"] NameValueCollection that contains a single "to" key with multiple values, which appears to be an object of type System.Collections.Specialized.NameObjectCollectionBase.NameObjectEntry
I'm sure I'm missing something simple. I haven't been able to figure out how to iterate over this collection and get each individual value. I'd be looking for something like this, which obviously doesn't work:
foreach (String address in mailTo["to"])
{
message.To.Add(new MailAddress(address));
}
Additionally, if you know a better way to go from mailto URI to SMTP message I'm all eyes.
To answer your question without offering an alternative solution, try this:
foreach (var value in mailTo.GetValues("to"))
{
Debug.WriteLine(value);
}
the value part of the NameValueCollection is a string. So for the "to" key it would be a comma delimited string of email addresses.
string s = "to=address1@email.com&to=address2@email.com&to=address3@email.com&subject=test";
var items = System.Web.HttpUtility.ParseQueryString(s);
foreach(string email in items["to"].Split(','))
{
Console.Out.WriteLine(email);
}
results in the following
address1@email.com
address2@email.com
address3@email.com
The mailTo["to"] is simply a string that contains the comma-separated addresses which you can split and parse like this:
foreach (var address in mailTo["to"].Split(','))
{
message.To.Add(new MailAddress(address));
}
精彩评论