内存流长度始终为零

Memory stream length always zero

当运行以下代码时,我的内存流的长度始终为零(documentStream.length)

我已经尝试将位置重置为零,这似乎解决了大多数问题,但我仍然得到零长度?

public MemoryStream CreateDocumentTest()
    {
        MemoryStream documentStream = new MemoryStream();

        WordprocessingDocument wordDocument =
            WordprocessingDocument.Create(documentStream, WordprocessingDocumentType.Document);

        MainDocumentPart mainPart = wordDocument.AddMainDocumentPart();

        mainPart.Document = new Document();
        Body body = mainPart.Document.AppendChild(new Body());
        Paragraph para = body.AppendChild(new Paragraph());
        Run run = para.AppendChild(new Run());
        run.AppendChild(new Text("Create text in body - CreateWordprocessingDocument"));

        wordDocument.MainDocumentPart.Document.Save();
        wordDocument.Save();
        documentStream.Seek(0, SeekOrigin.Begin);

        return documentStream;
    }

我是如何解决这个问题的,我将 CreateDocumentTest 方法调整为无效,并且我有一个 public 属性 for MemoryStream

我也用“Using (WordprocessingDocument wordDocument...)”包裹了建筑,并通过设置我的 public 属性

结束了方法

现在,我不确定它是在使用 public 属性,还是在应用“using”,或者两者兼而有之,但它现在可以工作了……这是更新后的代码

        public void CreateDocumentTest()
        {

            DocumentStream = new MemoryStream();

            using (WordprocessingDocument wordDocument =
                WordprocessingDocument.Create(DocumentStream, WordprocessingDocumentType.Document))
            {
                MainDocumentPart mainPart = wordDocument.AddMainDocumentPart();

                mainPart.Document = new Document();
                Body body = mainPart.Document.AppendChild(new Body());
                Paragraph para = body.AppendChild(new Paragraph());
                Run run = para.AppendChild(new Run());
                run.AppendChild(new Text("Create text in body - CreateWordprocessingDocument"));

                wordDocument.MainDocumentPart.Document.Save();

                DocumentStream.Seek(0, SeekOrigin.Begin);
            }
        }