2013-03-21 32 views
5

我创建了一个应用程序,用于从某些数据库数据生成exel文件。生成文件后,它们会自动发送给相关客户。我的问题是,当我运行发布的应用程序时,它工作正常。但是有些用户在运行应用程序时会生成完美的文件,因为它们保存在硬盘上,我可以看到它们。但是当它们连接到MailMessage对象时,它们会被损坏。这是损坏文件的图像。这些文件应该是Excel文件。将它们附加到MailMessage时文件已损坏C#

enter image description here

这是我的邮件发送带有附件代码:

public void SendMailedFilesDK() 
     { 
      string[] sentFiles = Directory.GetFiles(sentFilesDK); 
      if (sentFiles.Count() > 0) 
      { 
       using (System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient("ares")) 
       { 
        using (System.Net.Mail.MailMessage msg = new System.Net.Mail.MailMessage()) 
        { 
         msg.From = new MailAddress("[email protected]"); 
         msg.To.Add(new MailAddress("[email protected]")); 
         msg.To.Add(new MailAddress("[email protected]")); 
         msg.CC.Add("[email protected]"); 
         msg.CC.Add("[email protected]"); 
         msg.Subject = "IBM PUDO"; 
         msg.Body = sentFiles.Count() + " attached file(s) has been sent to the customer(s) in question "; 
         msg.IsBodyHtml = true; 
         foreach (string file in sentFiles) 
         { 
          Attachment attachment = new Attachment(file); 
          msg.Attachments.Add(attachment); 
         } 

         client.Send(msg); 
        } 
       } 
      } 
     } 

为什么文件越来越损坏当别人运行应用程序?我们都在使用office 2010.

回答

1

您应该确保将附件的内容类型设置为适当的值。

application/vnd.openxmlformats-officedocument.spreadsheetml.sheet为XLSX文件,或

application/vnd.ms-excel为XLS文件。

例如,你的循环应该看起来像这样。

ContentType xlsxContent = new ContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" 
foreach (string file in sentFiles) 
{ 
    Attachment attachment = new Attachment(file, xlsxContent); 
    msg.Attachments.Add(attachment); 
} 
+0

如果它是我需要attatch的Zip文件,我应该写什么?我试图插入这一行:**附件附件=新的附件(zipFile,MediaTypeNames.Application.Zip); **但它没有奏效。我正在使用** DotNetZipLib-DevKit-v1.9 ** – Lahib 2013-03-22 09:56:48

+0

发现它。我必须使用'application/zip' – Lahib 2013-03-22 10:07:48

0

您可能想要指定属于Attachment类构造函数之一的mimetype。

public Attachment(string fileName,ContentType contentType);

您还可以读取memorystream中的文件并将其作为以下构造函数的一部分传递。

public Attachment(Stream contentStream,string name,string mediaType);

1

我们在我们的Attachment构造函数中使用它,并且没有附加Excel和PDF的问题。

Attachment data = new Attachment(sFileName,MediaTypeNames.Application.Octet);

此外,请检查运行此操作的用户是否有权访问sentFilesDK指定的任何位置的文件。