如何在C#中使用Microsoft Graph v5下载共享邮箱指定附件
通过Microsoft Graph API下载共享邮箱附件的解决方法
你的代码问题在于直接将Attachment对象传给File.WriteAllBytes,而该方法需要的是字节数组,且路径必须包含完整文件名。以下是修正后的实现步骤:
- 先判断附件类型:只有
FileAttachment类型的附件才包含ContentBytes属性,需要将获取到的通用Attachment转换为FileAttachment。 - 指定完整保存路径:
File.WriteAllBytes要求传入包含文件名的完整路径,不能仅传目录。 - 写入字节数组:提取
FileAttachment的ContentBytes并写入文件。
修正后的代码:
if (attachmentId != null) { var attachment = await graphServiceClient.Users[email].Messages[messageId].Attachments[attachmentId.Id].GetAsync(); // 过滤出文件类型的附件 if (attachment is FileAttachment fileAttachment) { // 组合保存路径(目录+原附件文件名) string fullSavePath = Path.Combine(@"D:\", fileAttachment.Name); // 将附件字节写入文件 File.WriteAllBytes(fullSavePath, fileAttachment.ContentBytes); } }
额外注意事项:
- 确保你的应用已正确申请权限:委托权限需
Mail.Read,应用权限需Mail.Read.All,且已授权访问目标共享邮箱。 - 如果附件较大(超过4MB),建议使用增量下载方式,调用
Attachments.Content.GetAsync()获取流式内容,避免内存占用过高。示例代码:
if (attachmentId != null) { var attachment = await graphServiceClient.Users[email].Messages[messageId].Attachments[attachmentId.Id].GetAsync(); using var stream = await graphServiceClient.Users[email].Messages[messageId].Attachments[attachmentId.Id].Content.GetAsync(); string fullSavePath = Path.Combine(@"D:\", attachment.Name); using var fileStream = new FileStream(fullSavePath, FileMode.Create); await stream.CopyToAsync(fileStream); }
内容的提问来源于stack exchange,提问作者Shishank
相关产品推荐
相关产品推荐

