简体   繁体   中英

Convert open xml string to byte[]

so, I am editing a word document, using OpenXML. And for some reasons, I convert it all into a string :

//conversion du byte en memorystream
using (var file = new MemoryStream(text))
using (var reader = new StreamReader(file))
{
    WordprocessingDocument wordDoc = WordprocessingDocument.Open(file, true);
    using (StreamReader sr = new StreamReader(wordDoc.MainDocumentPart.GetStream()))
    {
        docText = sr.ReadToEnd();
    }
}

And then, I convert it as a byte.

But, a simple convert will not work:

byte[] back2Byte = System.Text.Encoding.ASCII.GetBytes(docText );

Because the string is a open xml string.

Tried this, but always got a corrupted file when I tried to open it with Word:

var repo = new System.IO.MemoryStream(System.Text.Encoding.UTF8.GetBytes(docText));

byte[] buffer = new byte[16 * 1024];
MemoryStream ms = new MemoryStream();

int read;
while ((read = repo.Read(buffer, 0, buffer.Length)) > 0)
{
    ms.Write(buffer, 0, read);
}

byte[] back2Byte = ms.ToArray();

So, this doesn't work either:

byte[] back2Byte = new byte[docText.Length * sizeof(char)];
System.Buffer.BlockCopy(docText.ToCharArray(), 0, back2Byte, 0, back2Byte.Length);

edit : After some checkings, it seems it is write as a openxml document into the database, and so, word cannot read it. There is no error when i open it with notepad

How can I correct this?

So, the real issue is, how can I convert a OpenXML string to a byte that can be open in word?

You cannot do this sort of thing. You are getting the bytes for only one part of an OpenXML document. By definition, all Microsoft Office documents are multi-part OpenXML documents. You could theoretically capture the bytes for all the parts using a technique like you're currently using, but you would also have to capture all the part/relationship information necessary to reconstruct the multi-part document. You'd be better off just reading all the bytes of the file and storing them as-is:

// to read the file as bytes
var fileName = @"C:\path\to\the\file.xlsx";
var fileBytes = File.ReadAllBytes(fileName);

// to recreate the file from the bytes
File.WriteAllBytes(fileName, fileBytes)

If you need a string form of those bytes, try this:

// to convert bytes to a (non-readable) text form
var fileContent = Convert.ToBase64String(fileBytes);

// to convert base-64 back to bytes
var fileBytes = Convert.FromBase64String(fileContent);

Either way, there is absolutely no need to use the OpenXML SDK for your use case.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM