Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Word document to base64 string C#

I'm trying to get the base64 representation of an active Word document while it's still open in Word and am getting the following error in ReadAllBytes():

The process cannot access the file 'file path' it is being used by another process

public string GetEncodedTemplate()
        {
            //Convert a Word document's base64 representation
            string base64 = String.Empty;
            _application.ActiveDocument.Save();

            string docPath = _application.ActiveDocument.FullName;
            byte[] binarydata = File.ReadAllBytes(docPath);
            base64 = System.Convert.ToBase64String(binarydata, 0, binarydata.Length);
            return base64;
        }

I do understand that the error occurs because the specified document is still open in Word, my question is - Is it still somehow possible to get the base64 representation of the document without resorting to saving to a temp file?

I'm using C# .NET 4.0 And MS Office 2010

like image 542
Denys Wessels Avatar asked Jul 19 '12 14:07

Denys Wessels


People also ask

How do I convert a file to Base64?

Convert Files to Base64 Just select your file or drag & drop it below, press the Convert to Base64 button, and you'll get a base64 string. Press a button – get base64. No ads, nonsense, or garbage. The input file can also be an mp3 or mp4.

How do I encode a string in Base64?

If we were to Base64 encode a string we would follow these steps: Take the ASCII value of each character in the string. Calculate the 8-bit binary equivalent of the ASCII values. Convert the 8-bit chunks into chunks of 6 bits by simply re-grouping the digits.

Can you Base64 encode a file?

Base64 is an encoding algorithm that converts any characters, binary data, and even images or sound files into a readable string, which can be saved or transported over the network without data loss. The characters generated from Base64 encoding consist of Latin letters, digits, plus, and slash.


1 Answers

You are correct - Word has a lock on the current document. In order to get the current document bytes you would need to copy the existing file (File.Copy) or save to a new file (Document.SaveAs or IPersistFile.Save) for reading its content.

like image 165
SliverNinja - MSFT Avatar answered Nov 07 '22 07:11

SliverNinja - MSFT