我有以下代码来枚举我的联系人的所有电子邮件地址,但我无法使用此行的例外点
Outlook.ContactItem oAppt = (Outlook.ContactItem)oItems;
有人可以帮助我,以便我可以枚举Microsoft Outlook中我的联系人的所有电子邮件地址吗?
namespace RetrieveContacts
{
public class Class1
{
public static int Main(string[] args)
{
try
{
Outlook.Application oApp = new Outlook.Application();
Outlook.NameSpace oNS = oApp.GetNamespace("mapi");
Outlook.MAPIFolder oContacts = oNS.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderContacts);
Outlook.Items oItems = oContacts.Items;
Outlook.ContactItem oAppt = (Outlook.ContactItem)oItems;
for (int i = 0; i <= oItems.Count; i++)
{
System.IO.StreamWriter file = new System.IO.StreamWriter("C:\\EmailAddress.txt");
file.WriteLine(oAppt.Email1Address);
file.Close();
}
oNS.Logoff();
oAppt = null;
oItems = null;
oContacts = null;
oNS = null;
oApp = null;
}
catch (Exception e)
{
System.IO.StreamWriter file = new System.IO.StreamWriter("C:\\Exception.txt");
file.WriteLine(e);
file.Close();
}
return 0;
}
}
}
答案 0 :(得分:0)
不知道Outlook的对象模型我猜测Outlook.Items
是ContactItem
的集合,因此无法直接转换为单个ContactItem
}。其他问题:
ContactItem
,否则您的演员会抛出错误。using
块中,以便在抛出异常时自动关闭0
转到Count
,如果它应该从0
转到Count-1
尝试将循环更改为以下内容:
Outlook.Items oItems = oContacts.Items;
using(System.IO.StreamWriter file = new System.IO.StreamWriter("C:\\EmailAddress.txt"))
{
for (int i = 0; i < oItems.Count; i++) // Note < instead of <=
{
// Will be null if oItems[i] is not a ContactItem
Outlook.ContactItem oAppt = oItems[i] as Outlook.ContactItem;
if(oAppt != null)
file.WriteLine(oAppt.Email1Address);
}
}
file.Close();
oNS.Logoff();