1 //----------------------------------------------------------------------------- 2 // <copyright file="MailAddressCollection.cs" company="Microsoft"> 3 // Copyright (c) Microsoft Corporation. All rights reserved. 4 // </copyright> 5 //----------------------------------------------------------------------------- 6 7 namespace System.Net.Mail 8 { 9 using System; 10 using System.Collections; 11 using System.Collections.Generic; 12 using System.Collections.ObjectModel; 13 using System.Text; 14 using System.Net.Mime; 15 16 public class MailAddressCollection: Collection<MailAddress> { MailAddressCollection()17 public MailAddressCollection(){ 18 } 19 Add(string addresses)20 public void Add(string addresses) { 21 if (addresses == null) { 22 throw new ArgumentNullException("addresses"); 23 } 24 if (addresses == string.Empty) { 25 throw new ArgumentException(SR.GetString(SR.net_emptystringcall, "addresses"), "addresses"); 26 } 27 28 ParseValue(addresses); 29 } 30 SetItem(int index, MailAddress item)31 protected override void SetItem(int index, MailAddress item){ 32 if(item==null) { 33 throw new ArgumentNullException("item"); 34 } 35 36 base.SetItem(index,item); 37 } 38 InsertItem(int index, MailAddress item)39 protected override void InsertItem(int index, MailAddress item){ 40 if(item==null){ 41 throw new ArgumentNullException("item"); 42 } 43 44 base.InsertItem(index,item); 45 } 46 ParseValue(string addresses)47 internal void ParseValue(string addresses){ 48 IList<MailAddress> result = MailAddressParser.ParseMultipleAddresses(addresses); 49 50 for (int i = 0; i < result.Count; i++) { 51 this.Add(result[i]); 52 } 53 } 54 ToString()55 public override string ToString(){ 56 bool first = true; 57 StringBuilder builder = new StringBuilder(); 58 59 foreach (MailAddress address in this) { 60 if (!first) { 61 builder.Append(", "); 62 } 63 64 builder.Append(address.ToString()); 65 first = false; 66 } 67 68 return builder.ToString();; 69 } 70 Encode(int charsConsumed, bool allowUnicode)71 internal string Encode(int charsConsumed, bool allowUnicode) { 72 string encodedAddresses = string.Empty; 73 74 //encode each address individually (except the first), fold and separate with a comma 75 foreach (MailAddress address in this) { 76 if (String.IsNullOrEmpty(encodedAddresses)) { 77 //no need to append a comma to the first one because it may be the only one. 78 encodedAddresses = address.Encode(charsConsumed, allowUnicode); 79 } 80 else { 81 //appending another one, append a comma to separate and then fold and add the encoded address 82 //the charsConsumed will be 1 because only the first line needs to account for the header itself for 83 //line length; subsequent lines have a single whitespace character because they are folded here 84 encodedAddresses += ", " + address.Encode(1, allowUnicode); 85 } 86 } 87 return encodedAddresses; 88 } 89 } 90 } 91