private static MailAddress ParseAddress(string data, bool expectMultipleAddresses, ref int index)
{
Debug.Assert(!string.IsNullOrEmpty(data));
Debug.Assert(index >= 0 && index < data.Length, "Index out of range: " + index + ", " + data.Length);
// Parsed components to be assembled as a MailAddress later
string domain = null;
string localPart = null;
string displayName = null;
// Skip comments and whitespace
index = ReadCfwsAndThrowIfIncomplete(data, index);
// Do we expect angle brackets around the address?
// e.g. ("display name" <user@domain>)
bool expectAngleBracket = false;
if (data[index] == MailBnfHelper.EndAngleBracket)
{
expectAngleBracket = true;
index--;
}
domain = ParseDomain(data, ref index);
// The next character after the domain must be the '@' symbol
if (data[index] != MailBnfHelper.At)
{
throw new FormatException(SR.MailAddressInvalidFormat);
}
// Skip the '@' symbol
index--;
localPart = ParseLocalPart(data, ref index, expectAngleBracket, expectMultipleAddresses);
// Check for a matching angle bracket around the address
if (expectAngleBracket)
{
if (index >= 0 && data[index] == MailBnfHelper.StartAngleBracket)
{
index--; // Skip the angle bracket
// Skip white spaces, but leave comments, as they may be part of the display name.
index = WhitespaceReader.ReadFwsReverse(data, index);
}
else
{
// Mismatched angle brackets, throw
throw new FormatException(SR.Format(SR.MailHeaderFieldInvalidCharacter,
(index >= 0 ? data[index] : MailBnfHelper.EndAngleBracket)));
}
}
// Is there anything left to parse?
// There could still be a display name or another address
if (index >= 0 && !(expectMultipleAddresses && data[index] == MailBnfHelper.Comma))
{
displayName = ParseDisplayName(data, ref index, expectMultipleAddresses);
}
else
{
displayName = string.Empty;
}
return new MailAddress(displayName, localPart, domain);
}