[英]How To Save Attachments object to RackSpace Cloud using C#?
我有一個“ System.Net.Mail.Attachment []附件”對象,該對象包含PDF,XLS,Doc或jpg文件。
我想將此附件對象保存到雲服務器。
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字節數據(損壞)文件。 我已經搜索了很多地方。 但是無法在代碼中找到錯誤。
在這種情況下,請提出一些解決方案?
看起來您正在使自己變得更加困難,然后需要。 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()),但這不是文件的內容。
經過如此多的研發,我想出了以下答案
附件對象的內存流對我不起作用。 因此,我進入了保存附件的臨時路徑,並執行以下神奇代碼:
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();
希望我的問題和答案對您的項目有所幫助
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.