簡體   English   中英

Word OpenXml Word 發現無法讀取的內容

[英]Word OpenXml Word Found Unreadable Content

我們正在嘗試根據某些條件操作 word 文檔以刪除段落。 但是當我們嘗試打開它並出現錯誤時,生成的單詞文件總是最終被損壞:

Word 發現無法讀取的內容

下面的代碼會損壞文件,但如果我們刪除該行:

Document document = mdp.Document;

文件被保存並打開沒有問題。 是否有我遺漏的明顯問題?

 var readAllBytes = File.ReadAllBytes(@"C:\Original.docx");


    using (var stream = new MemoryStream(readAllBytes))
    {
    using (WordprocessingDocument wpd = WordprocessingDocument.Open(stream, true))
    {
        MainDocumentPart mdp = wpd.MainDocumentPart;
        Document document = mdp.Document;

    }
}

File.WriteAllBytes(@"C:\New.docx", readAllBytes);

更新:

using (WordprocessingDocument wpd = WordprocessingDocument.Open(@"C:\Original.docx", true))
            {
                MainDocumentPart mdp = wpd.MainDocumentPart;
                Document document = mdp.Document;

                document.Save();
            }

在物理文件上運行上面的代碼,我們仍然可以打開 Original.docx 而不會出現錯誤,因此它似乎僅限於修改流。

這是一個將文檔讀入MemoryStream

public static MemoryStream ReadAllBytesToMemoryStream(string path)
{
    byte[] buffer = File.ReadAllBytes(path);
    var destStream = new MemoryStream(buffer.Length);
    destStream.Write(buffer, 0, buffer.Length);
    destStream.Seek(0, SeekOrigin.Begin);
    return destStream;
}

注意MemoryStream是如何實例化的。 我傳遞的是容量而不是緩沖區(如您自己的代碼)。 這是為什么?

使用MemoryStream()MemoryStream(int) ,您正在創建一個可調整大小的MemoryStream實例,以防您對文檔進行更改。 當使用MemoryStream(byte[]) (如在您的代碼中)時, MemoryStream實例不可調整大小,除非您不對文檔進行任何更改,否則您的更改只會使其尺寸縮小,否則這將是有問題的。

現在,要將 Word 文檔讀入MemoryStream ,在內存中操作該 Word 文檔,並最終獲得一致的MemoryStream ,您必須執行以下操作:

// Get a MemoryStream.
// In this example, the MemoryStream is created by reading a file stored
// in the file system. Depending on the Stream you "receive", it makes
// sense to copy the Stream to a MemoryStream before processing.
MemoryStream stream = ReadAllBytesToMemoryStream(@"C:\Original.docx");

// Open the Word document on the MemoryStream.
using (WordprocessingDocument wpd = WordprocessingDocument.Open(stream, true)
{
    MainDocumentPart mdp = wpd.MainDocumentPart;
    Document document = mdp.Document;
    // Manipulate document ...
}

// After having closed the WordprocessingDocument (by leaving the using statement),
// you can use the MemoryStream for whatever comes next, e.g., to write it to a
// file stored in the file system.
File.WriteAllBytes(@"C:\New.docx", stream.GetBuffer());

請注意,每當您的下一個操作取決於MemoryStream.Position屬性(例如CopyToCopyToAsync )時,您都必須通過調用stream.Seek(0, SeekOrigin.Begin)來重置stream.Position屬性。 在離開 using 語句之后,流的位置將等於其長度。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM