2016-02-08 56 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(); 

我希望我的问题和答案可以帮助您为您的项目

相关问题