2013-03-21 31 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指定的任何位置的文件。