【问题标题】:Save email attachment to excel file corrupts file将电子邮件附件保存到 Excel 文件损坏的文件
【发布时间】:2019-11-27 03:58:36
【问题描述】:

我有一个包含附件的System.Net.Mail.MailMessage,当将它们保存为文件时,所有 Excel 文件都已损坏,之后我无法打开它们。 它适用于 PDF 文件。

有人有一些适用于 Excel 文件的代码吗? .xlsx 和 .xlsm

我尝试了不同版本的代码,但每次文件都损坏了

Dim buffer(convert.ToInt32(attachment.ContentStream.Length)) As Byte
Dim file As FileStream

attachment.ContentStream.Read(buffer, 0, buffer.Length)

file = New FileStream("C:\example.xlsx", FileMode.OpenOrCreate, FileAccess.ReadWrite)

file.Write(buffer, 0, buffer.Length)

file.Dispose()

我希望能够像使用 PDF 一样使用作为附件发送的 excel 文件

【问题讨论】:

  • 欢迎来到 SO。请您在问题中标记您的代码以使其更清晰。
  • 您确定附件本身没有损坏吗?你能从邮件客户端成功打开文件吗?
  • FileMode.OpenOrCreate 是错误的选项,你想要FileMode.Create 否则,如果之前有一个同名但更长的文件,则结尾部分不会被截断,Excel 会认为它是损坏。
  • 例如如果您有一个内容为“11111”的现有文件“example.dat”,并且您使用FileMode.OpenOrCreate 向其写入新内容“222”,您最终将得到内容“22211”。
  • 我也尝试过使用 create,但我仍然得到一个损坏的文件。附件本身没有损坏,电子邮件是我自己发送的。

标签: .net excel vb.net mailmessage


【解决方案1】:

我不确定为什么不这样做,但我希望这会起作用:

Using fs = File.Create("file path here")
    attachment.ContentStream.CopyTo(fs)
End Using

【讨论】:

    猜你喜欢
    • 2018-03-24
    • 1970-01-01
    • 1970-01-01
    • 2012-05-17
    • 2010-09-23
    • 1970-01-01
    • 2016-06-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多