/// <summary>Adds <see cref="T:System.Net.Cookie" /> instances for one or more cookies from an HTTP cookie header to the <see cref="T:System.Net.CookieContainer" /> for a specific URI.</summary> /// <param name="uri">The URI of the <see cref="T:System.Net.CookieCollection" />. </param> /// <param name="cookieHeader">The contents of an HTTP set-cookie header as returned by a HTTP server, with <see cref="T:System.Net.Cookie" /> instances delimited by commas. </param> /// <exception cref="T:System.ArgumentNullException"> /// <paramref name="uri" /> is null. </exception> /// <exception cref="T:System.ArgumentNullException"> /// <paramref name="cookieHeader" /> is null. </exception> /// <exception cref="T:System.Net.CookieException">One of the cookies is invalid. -or- An error occurred while adding one of the cookies to the container. </exception> public void SetCookies(System.Uri uri, string cookieHeader) { if (uri == null) { throw new ArgumentNullException("uri"); } if (cookieHeader == null) { throw new ArgumentNullException("cookieHeader"); } if (cookieHeader.Length == 0) { return; } string[] array = cookieHeader.Split(new char[] { ',' }); for (int i = 0; i < array.Length; i++) { string text = array[i]; if (array.Length > i + 1 && System.Text.RegularExpressions.Regex.IsMatch(array[i], ".*expires\\s*=\\s*(Mon|Tue|Wed|Thu|Fri|Sat|Sun)", System.Text.RegularExpressions.RegexOptions.IgnoreCase) && System.Text.RegularExpressions.Regex.IsMatch(array[i + 1], "\\s\\d{2}-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-\\d{4} \\d{2}:\\d{2}:\\d{2} GMT", System.Text.RegularExpressions.RegexOptions.IgnoreCase)) { text = new StringBuilder(text).Append(",").Append(array[++i]).ToString(); } try { Cookie cookie = CookieContainer.Parse(text); if (cookie.Path.Length == 0) { cookie.Path = uri.AbsolutePath; } else if (!uri.AbsolutePath.StartsWith(cookie.Path)) { string msg = string.Format("'Path'='{0}' is invalid with URI", cookie.Path); throw new CookieException(msg); } if (cookie.Domain.Length == 0) { cookie.Domain = uri.Host; cookie.ExactDomain = true; } this.AddCookie(cookie); } catch (Exception e) { string msg2 = string.Format("Could not parse cookies for '{0}'.", uri); throw new CookieException(msg2, e); } } }