【问题标题】:How To Save Attachments object to RackSpace Cloud using C#?如何使用 C# 将附件对象保存到 RackSpace Cloud?
【发布时间】:2016-02-08 13:33:54
【问题描述】:

我有一个 'System.Net.Mail.Attachment[] 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 字节数据(损坏)文件。 我已经为此搜索了很多地方。 但无法在代码中找到错误。

请在这种情况下提出一些解决方案?

【问题讨论】:

    标签: c# file cloud rackspace


    【解决方案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() 被调用),而这不是您文件的内容。

    【讨论】:

    • 感谢您的回答。 'attachments[intI].ContentStream' 是我最初尝试过的。这也是用0B保存文件。所以问题并没有得到解决。请进一步帮助我
    【解决方案2】:

    经过这么多的研发,我想出了以下答案

    附件对象的内存流对我不起作用。 所以我已经接近保存附件的临时路径并执行以下神奇代码:

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

    希望我的问题和回答对您的项目有所帮助

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-02-12
      • 1970-01-01
      • 1970-01-01
      • 2016-08-15
      • 1970-01-01
      • 2016-09-05
      • 2013-02-22
      相关资源
      最近更新 更多