.NET 6 C#实现Outlook拖拽邮件到OneNote添加附件功能求助
解决Outlook拖拽插件添加非内嵌附件到OneNote的方案
1. 筛选邮件中的非内嵌附件
先从拖拽的邮件对象中提取并筛选出非内嵌附件:
// 从拖拽数据中获取Outlook邮件对象 if (e.Data.GetDataPresent("Outlook.Message")) { Outlook.MailItem mailItem = e.Data.GetData("Outlook.Message") as Outlook.MailItem; foreach (Outlook.Attachment attachment in mailItem.Attachments) { // 通过附件类型和MAPI属性判断是否为非内嵌附件 bool isInlineAttachment = attachment.Type == Outlook.OlAttachmentType.olEmbeddeditem || (attachment.PropertyAccessor != null && (bool)attachment.PropertyAccessor.GetProperty("http://schemas.microsoft.com/mapi/proptag/0x7FFE000B")); if (!isInlineAttachment) { // 处理该非内嵌附件 HandleAttachment(attachment); } } }
2. 临时保存附件到本地
OneNote添加附件需要本地文件路径,先将附件保存到临时目录:
private string SaveTempAttachment(Outlook.Attachment attachment) { string tempDir = Path.GetTempPath(); string tempFilePath = Path.Combine(tempDir, attachment.FileName); // 避免文件名重复 if (File.Exists(tempFilePath)) { tempFilePath = Path.Combine(tempDir, $"{Path.GetFileNameWithoutExtension(attachment.FileName)}_{Guid.NewGuid()}{Path.GetExtension(attachment.FileName)}"); } attachment.SaveAsFile(tempFilePath); return tempFilePath; }
3. 将附件插入OneNote页面
通过OneNote Interop把附件添加到已创建的页面中:
private void InsertAttachmentToOneNote(string targetPageId, string attachmentPath) { var oneNoteApp = new Microsoft.Office.Interop.OneNote.Application(); string pageXml = string.Empty; // 获取目标页面的XML内容 oneNoteApp.GetPageContent(targetPageId, out pageXml, Microsoft.Office.Interop.OneNote.PageInfo.piAll); // 解析XML并构造附件节点 XmlDocument doc = new XmlDocument(); doc.LoadXml(pageXml); XmlNamespaceManager nsManager = new XmlNamespaceManager(doc.NameTable); nsManager.AddNamespace("one", "http://schemas.microsoft.com/office/onenote/2013/onenote"); XmlElement attachmentNode = doc.CreateElement("one:File", "http://schemas.microsoft.com/office/onenote/2013/onenote"); attachmentNode.SetAttribute("path", attachmentPath); attachmentNode.SetAttribute("displayName", Path.GetFileName(attachmentPath)); // 将附件节点插入页面Body末尾 XmlNode bodyNode = doc.SelectSingleNode("//one:Body", nsManager); bodyNode.AppendChild(attachmentNode); // 更新OneNote页面内容 oneNoteApp.UpdatePageContent(doc.OuterXml); // 清理临时文件 File.Delete(attachmentPath); }
关键注意事项
- 确保项目已引用
Microsoft.Office.Interop.Outlook和Microsoft.Office.Interop.OneNote程序集 - 处理大附件时建议用异步逻辑,避免UI阻塞
- 验证临时目录的读写权限,确保附件能正常保存
内容的提问来源于stack exchange,提问作者Dimitry Okken
相关产品推荐
相关产品推荐

