简体   繁体   中英

How To Save Attachments object to RackSpace Cloud using C#?

I Have one 'System.Net.Mail.Attachment[] attachment' object , This object contains PDF,Xls,Doc or jpg file.

I want to save this attachment object to cloud server.

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();
}

I have used the above code to save the file. The File is saved to cloud but having 0 Byte data (Corrupted) File. I have searched many places for that. But not able to find error in the code.

Please suggest some solution in this case ?

Looks like you are making it yourself more difficult then needed. The Attachment instance has an ContentStream property which you don't need to feed through a MemoryStream at all.

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

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

If you are doing this:

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

You are probably writing the string representation of Attachment (ToString() gets called) and that is not the content of your file.

After so much r&d ,I have come up with the following answer

Memory stream of attachment object didn't work for me. So I have approached temp path where the attachement was saved and do the following magical code :

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();

I hope my question and answer helps you for your project

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM