You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Document Generation生成的Word附件下载损坏问题求助(C#)

Fixing Corrupted Document Generation Attachments in Dynamics 365

Hey there, let's figure out why your Document Generation-generated Word files are coming out corrupted (and only 2KB) when you download them via your C# code, while manually uploaded files work perfectly.

First, let's look at your current code snippet:

var filebody_ = NotesAttachment.GetAttributeValue<string>("documentbody"); 
byte[] bytes = Convert.FromBase64String(filebody); 
File.WriteAllBytes(@"C:\Users\DOCS\Test.docx", bytes);

(Quick note: You have a variable name mismatch here—filebody_ vs filebody—but since manual uploads work, I assume that's just a typo when sharing the code.)

The Root Cause

The key difference lies in how Dynamics 365 stores the documentbody value for the two types of files:

  • Manual uploads: The documentbody is a direct Base64 encoding of the raw file content, so your current code decodes it correctly.
  • Document Generation files: These are stored with their documentbody as a GZIP-compressed Base64 string (to save storage space). When you decode this directly without decompressing, you end up with compressed data instead of the actual Word file—hence the tiny, corrupted output.

The Fix

You need to add a step to decompress the bytes if they're GZIP-compressed. Here's how to modify your code to handle both file types:

var filebody = NotesAttachment.GetAttributeValue<string>("documentbody");
byte[] bytes = Convert.FromBase64String(filebody);

// Attempt to decompress GZIP content (for generated documents)
try
{
    using (var compressedStream = new MemoryStream(bytes))
    using (var gzipStream = new GZipStream(compressedStream, CompressionMode.Decompress))
    using (var resultStream = new MemoryStream())
    {
        gzipStream.CopyTo(resultStream);
        bytes = resultStream.ToArray();
    }
}
catch (InvalidDataException)
{
    // If the content isn't GZIP-compressed (like manual uploads), keep the original bytes
}

File.WriteAllBytes(@"C:\Users\DOCS\Test.docx", bytes);

Extra Checks to Confirm

  1. Verify GZIP signature: You can check if the decoded bytes start with the GZIP magic numbers (0x1F 0x8B)—this confirms the content is compressed.
  2. Check the mimetype attribute: For generated files, the mimetype will still reflect the actual file type (like application/vnd.openxmlformats-officedocument.wordprocessingml.document), but the underlying storage remains compressed regardless.

This adjustment should let you save and open both manually uploaded and Document Generation-generated files without any corruption issues.

内容的提问来源于stack exchange,提问作者Anish

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 10:06:49