我正在使用Office 365中的Outlook,这是C#中的代码我必须删除"已删除项目中的项目"夹。
执行此转换时出错:
var idList = (from MailItem item in binFolder.Items select item.EntryID).ToList();
这是完整的代码:
public void DeleteBin()
{
ApplicationClass outlookApp = new ApplicationClass();
var binFolder = outlookApp.Session
.GetDefaultFolder(OlDefaultFolders.olFolderDeletedItems);
var idList = (from MailItem item in binFolder.Items select item.EntryID).ToList();
DeleteFromId(idList);
}
// It gets a list of emails ID and remove it from the outlook
private void DeleteFromId(List<string> idList)
{
foreach (var id in idList)
{
var item = (MailItem)mapiNameSpace.GetItemFromID(id);
item.Delete();
}
}
由于
答案 0 :(得分:0)
如果行中出现错误
var idList = (from MailItem item in binFolder.Items select item.EntryID).ToList();
它有几个原因:
MailItem
类型。EntryID
属性时可能会抛出异常。您可以通过如下转换Linq语句来预防/处理这类问题:
var idList = new List<string>();
foreach (var item in binFolder.Items.OfType<MailItem>())
{
try
{
idList.Add(item.EntryID);
}
catch (COMException ex)
{
Trace.WriteLine(ex);
}
}
这可以修复代码中的错误,但由于您不必再次检索每个项目,因此以下内容很可能会运行得更快:
var itemsToDelete = binFolder.Items.OfType<dynamic>().ToList();
foreach (var item in itemsToDelete)
{
try
{
item.Delete();
}
catch (Exception ex)
{
Trace.WriteLine(ex);
}
}