我正在尝试从C#Windows窗体应用中的Outlook 2010中的特定文件夹中获取附件。我有一个名为MailInbox的类,它包含Outlook命名空间,收件箱和消息对象。
以下是该类及其方法的代码:
public class mailInbox
{
//declare needed variables for outlook office interop
public Outlook.Application oApp = new Outlook.Application();
//public Outlook.MAPIFolder oInbox;
public Outlook.MAPIFolder idFolder;
public Outlook.NameSpace oNS;
public Outlook.Items oItems;
public Outlook.MailItem oMsg;
public Outlook.MAPIFolder subFolder;
public string subFolderName;
public mailInbox()
{
//read the subfoldername from a text file
using (StreamReader subFolderNameRead = new StreamReader(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + @"\SuperVerify\config\subfoldername.txt"))
{
subFolderName = subFolderNameRead.ReadLine().Trim();
}
oNS = oApp.GetNamespace("mapi");
//oInbox = oNS.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox);
idFolder = oNS.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox).Folders[subFolderName]; // use the subFolderName string, read from the config text file, to get the folder from outlook
oItems = idFolder.Items;
//oMsg = (Outlook.MailItem)oItems.GetNext();
}
public void FetchEmail() // fetches the next email in the inbox and saves the attachments to the superverify folder
{
oNS.Logon(Missing.Value, Missing.Value, false, true); //login using default profile. This might need to be changed.
oMsg = (Outlook.MailItem) oItems.GetNext(); //fetch the next mail item in the inbox
if(oMsg.Attachments.Count > 0) // make sure message contains attachments **This is where the error occurs**
{
for (int i =0; i< oMsg.Attachments.Count; i++)
{
oMsg.Attachments[i].SaveAsFile(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + @"\SuperVerify\images\" + oMsg.Attachments[i].FileName); //save each attachment to the specified folder
}
} else //if no attachments, display error
{
MessageBox.Show("The inbox folder has no messages.", "TB ID Verification Tool", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
}
public void changeSubFolderName(string newSubFolderName)
{
subFolderName = newSubFolderName;
}
}
当我点击调用FetchEmail
方法的按钮时,我收到错误
System.NullReferenceException:'对象引用未设置为对象的实例。'
oMsg
为空。我以为
public Outlook.MailItem oMsg;
实例化对象和
oMsg = (Outlook.MailItem) oItems.GetNext();
为它分配了一个Outlook MailItem,但似乎我不明白这里发生了什么。
答案 0 :(得分:0)
来自the documentation奇怪地引用VB.NET的Nothing
而不是null,
如果没有下一个对象,则返回Nothing ,例如,如果已经位于集合的末尾,则返回Nothing。确保大型GetFirst,GetLast,GetNext和GetPrevious方法的正确操作集合,在该集合上调用GetNext之前调用GetFirst,并在调用GetPrevious之前调用GetLast。要确保始终对同一个集合进行调用,请在进入循环之前创建一个引用该集合的显式变量。
如果你在文件夹的末尾,GetNext
将返回null。在尝试使用它之前,您必须将其检查为null。
您还可以使用oItems.Count
确定最初访问文件夹项目时没有项目。但是,如果Count
是一个或多个,您仍然需要检查null,因为您正在处理可以更改的集合。假设有人可以在您阅读时从文件夹中删除项目,因此您无法预先计算,然后依赖它。