C# System.Runtime.InteropServices.COMException(0x80030020):操作失败

C# System.Runtime.InteropServices.COMException(0x80030020):操作失败,c#,office-interop,C#,Office Interop,我正在尝试使用以下命令将Outlook.MailItem保存到文件夹: MailItem.SaveAs(路径,Outlook.OlSaveAsType.olMSG) 这在大多数情况下都很有效。然而,当一次有大约20封电子邮件访问Outlook时,对于其中一些邮件,我得到以下例外情况: System.Runtime.InteropServices.COMException (0x80030020): The operation failed. at Microsoft.Office.Inte

我正在尝试使用以下命令将
Outlook.MailItem
保存到文件夹:

MailItem.SaveAs(路径,Outlook.OlSaveAsType.olMSG)

这在大多数情况下都很有效。然而,当一次有大约20封电子邮件访问Outlook时,对于其中一些邮件,我得到以下例外情况:

System.Runtime.InteropServices.COMException (0x80030020): The operation failed.
   at Microsoft.Office.Interop.Outlook._MailItem.SaveAs(String Path, Object Type)
我检查了代码
0x80030020
,这似乎意味着“发生了股份违规”。但是,我不确定这是什么意思。在我的应用程序中,我有以下两行,第一行将电子邮件保存到文件夹,第二行尝试将该文件发布到API:

file = MailItemHelper.SaveMailItemToOFEFolder(mailItem);
bool isEmailSentByHttp = MailItemHelper.SendMailItemToOFEApi(_userid, file)
路径具有电子邮件的主题,通过执行以下操作清除该主题以删除非字母数字字符:

Regex nonAlphaNumericRgx = new Regex(@"\W|_");
subject = nonAlphaNumericRgx.Replace(mail.Subject, "_");

我想我不能直接告诉你问题出在哪里,但我可以试着给你一些建议

根据,Outlook似乎正在使用
StgOpenStorage
函数,抛出
STG_E_SHAREVIOLATION
错误:

访问被拒绝,因为另一个调用者打开并锁定了文件

这意味着任何一个Outlook都在混乱(用户点击了“消息”,并查看锁定文件或其他东西),或者在用ReGEX更改文件名之后,您的字符串最终与另一个文件相同,而在写入另一个文件时,

您如何连接outlook?每收到一封邮件,你的应用程序是否使用新线程?您可以添加一个log4net并在代码中记录所有操作,如:

// receive and email and store subject name on var subject
log.Info($"E mail with subject '{subject}' arrived.");
// convert name and save on var newSubject
log.Info($"Mail will be saved as '{newSubject}'.");
// notify the beginning of the operation
log.Info("Calling MailItemHelper.SaveMailItemToOFEFolder.");
// notify the end of the operation
log.Info("Mail saved successfully.");
// notify Post in REST API
log.Info("Sending in MailItemHelper.SendMailItemToOFEApi");
// notify end of Post in REST API
log.Info("MailItemHelper.SendMailItemToOFEApi sent");

这将清楚地了解如何检索所有邮件,如果存在一些线程问题,您可以检查哪些邮件首先完成/开始。

我认为您是对的。只有在极少数情况下,当大约20封邮件同时到达邮箱时,才会有一两封邮件抛出异常。