【问题标题】:Can't save edited docx file loaded in MemoryStream无法保存在 MemoryStream 中加载的已编辑 docx 文件
【发布时间】:2017-06-30 21:23:51
【问题描述】:

我在 C# 中有一个 WebAPI,我需要通过 POST 加载一个 Document,修改一些参数,并将其保存到 Azure Blob 帐户。

我可以读取文件,我可以修改参数,但是当我将它保存到Azure时,文档保存为原始文件。

/* file es del tipo System.Net.Http.StreamContent que viene en un POST */

byte[] byteArray = await file.ReadAsByteArrayAsync();
MemoryStream docStream = new MemoryStream();

docStream.Write(byteArray, 0, byteArray.Length);
docStream.Seek(0x00000000, SeekOrigin.Begin);

WordprocessingDocument doc = WordprocessingDocument.Open(docStream, true);
MainDocumentPart mainDocumentPart = doc.MainDocumentPart;

var descedants = mainDocumentPart.Document.Body.Descendants<SdtElement>();

var idRef = descedants.Where(c => c.FirstChild.Elements<SdtAlias>().Where(v => v.Val == "Asunto").Count() > 0).FirstOrDefault();
if (idRef != null && user != null)
{
    var tNomRef = idRef.Elements<SdtContentRun>().FirstOrDefault().FirstOrDefault();
    var textNomRef = (DocumentFormat.OpenXml.OpenXmlLeafTextElement)tNomRef.LastOrDefault();
    textNomRef.Text = info.idDocumento;
}

var titRef = descedants.Where(c => c.FirstChild.Elements<SdtAlias>().Where(v => v.Val == "Título").Count() > 0).FirstOrDefault();
if (titRef != null && user != null)
{
    var tNomRef = idRef.Elements<SdtContentRun>().FirstOrDefault().FirstOrDefault();
    var textNomRef = (DocumentFormat.OpenXml.OpenXmlLeafTextElement)tNomRef.LastOrDefault();
    textNomRef.Text = info.nomDocumento;
}

/* Este objeto se encarga de subir el archivo a un Blob Storage de Azure */
CloudBlockBlob blob = imagesContainer.GetBlockBlobReference(xNombre);
docStream.Position = 0;
blob.UploadFromStream(docStream);
docStream.Close();
docStream.Dispose();

【问题讨论】:

标签: c# azure asp.net-web-api2 memorystream


【解决方案1】:

您正在从流中填充 DOM 结构。

除非您实际将其保存回某处,否则原始流不会受到影响。

您应该创建一个新流并将编辑后的文档保存到其中。

【讨论】:

  • 您好 SLaks,感谢您的回复,但我该怎么做呢?我尝试创建一个新的 MemoryStream,但是当我将文档保存到其中时,MemoryStream 关​​闭,我无法读取它或将其上传到 Azure。
  • @JuanRíos:使用ToArray()
  • 我想我不明白,如果我将实际的MemoryStream转换为Byte Array,文件是一样的。我会遗漏什么?
【解决方案2】:

doc(WordprocessingDocument) 修改后,您需要先将更改保存回 docStream(MemoryStream),然后再将 docStream 上传到 blob 存储。您需要做的只是在上传 docStream 之前添加 doc.Save()。下面的代码供您参考。

doc.Save();

CloudBlockBlob blob = imagesContainer.GetBlockBlobReference(xNombre);
docStream.Position = 0;

【讨论】:

  • 非常感谢您的评论。我将它添加到我的代码中,最后它可以工作了。
  • doc.Save(); byte[] newArray = docStream.ToArray(); blob.UploadFromByteArray(newArray, 0, newArray.Length);
猜你喜欢
  • 2016-08-23
  • 2012-01-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-28
  • 1970-01-01
  • 2017-08-15
  • 2020-07-18
相关资源
最近更新 更多