2016-02-08 57 views
0

我有一個'System.Net.Mail.Attachment []附件'對象,該對象包含PDF,Xls,Doc或jpg文件。如何使用C#將附件對象保存到RackSpace Cloud?

我想將此附件對象保存到雲服務器。

string sSavePath = "EmailAttachment/" + intSomeid + "/"; 
    string strErrorMsg = string.Empty; 

if ((attachments != null)) 
          { 
    MemoryStream memoryStream = new MemoryStream(); 
    StreamWriter memoryWriter = new StreamWriter(memoryStream); 
    memoryWriter.Write(attachments[0]); 
    memoryStream.Position = 0; 
    CloudFileSystem.SaveFileToCloudSystem(memoryStream, ref strErrorMsg, sSavePath, ConfigHelper.PrivateContainer, attachments[intI].Name); 
    memoryWriter.Dispose(); 
    memoryStream.Dispose(); 
} 

我已經使用上面的代碼來保存文件。 文件被保存到雲,但有0字節數據(損壞)的文件。 我搜索了很多地方。 但無法找到代碼中的錯誤。

請在這種情況下建議一些解決方案?

回答

1

看起來像你正在使自己更加困難,然後需要。 Attachment實例有一個ContentStream屬性,您根本不需要通過MemoryStream進行饋送。

string sSavePath = "EmailAttachment/" + intSomeid + "/"; 
string strErrorMsg = string.Empty; 

if ((attachments != null)) 
{ 
    CloudFileSystem.SaveFileToCloudSystem(
    attachments[intI].ContentStream, 
    ref strErrorMsg, 
    sSavePath, 
    ConfigHelper.PrivateContainer, 
    attachments[intI].Name); 
} 

如果你這樣做:

MemoryStream memoryStream = new MemoryStream(); 
StreamWriter memoryWriter = new StreamWriter(memoryStream); 
memoryWriter.Write(attachments[0]); 

你很可能編寫的Attachment字符串表示(toString()方法被調用),這是不是你的文件的內容。

+0

謝謝您的回答。 '附件[intI] .ContentStream'是我最初嘗試過的。這也是用0B保存文件。所以問題不是解決這個問題。請進一步幫助我 – ParthKansara

0

這麼多[R & d後,我想出瞭如下回答聯接對象的

內存流並沒有爲我工作。 其中attachement保存並執行以下代碼神奇所以我走近臨時路徑:

string FileName = ((System.IO.FileStream (attachments[intI].ContentStream)).Name; 
MemoryStream ms = new MemoryStream(); 
using (FileStream file = new FileStream(FileName, FileMode.Open, FileAccess.Read)) 
{ 
byte[] bytes = new byte[file.Length]; 
file.Read(bytes, 0, (int)file.Length); 
ms.Write(bytes, 0, (int)file.Length); 
} 
ms.Position = 0; 

CloudFileSystem.SaveFileToCloudSystem(ms, ref strErrorMsg, sSavePath, ConfigHelper.PrivateContainer, attachments[intI].Name); 
ms.Dispose(); 

我希望我的問題和答案可以幫助您爲您的項目

相關問題