How can i write and read Microsoft Word .docx files using StreamWriter?

Hi.
I am working on a project, and i need to be able to open a Microsoft word file outside of Unity.
Unfortunantely i can’t open the .docx If i Edit the file using StreamWriter, if i try, Microsoft Word Crashes with the following report:

![1]
I can however Read it through StreamWriter.
Anyone know how to prevent this?
Here is the Code i used:
#pragma strict

import System.IO;
var input = “”;
var filePath = “test.txt”;



function Update() {
if (Input.GetKeyDown(“r”)) {
WriteFile(filePath);
}
if (Input.GetKeyDown(“f”)) {
ReadFile(filePath);
}
}

function WriteFile(filepathIncludingFileName : String)
{
var sw : StreamWriter = new StreamWriter(filepathIncludingFileName);
sw.WriteLine(“Name:”);
sw.Flush();
sw.Close();
}

function ReadFile(filepathIncludingFileName : String) {
var sr : StreamReader = new StreamReader(filepathIncludingFileName);

input = “”;
while (true) {
input = sr.ReadLine();
if (input == null) { break; }
Debug.Log(“line=”+input);
}
sr.Close();
}
Thank you for taking your time reading this, i’m looking forward to your response :smiley:

So that script looks fine, but you’re not writing a .docx file, you’re writing a .txt file. If you then try to open it as a docx you’re going to have problems because they’re not the same thing at all.

Writing a docx file is far more complicated than just putting text in a file. 10 Seconds of googling turned up this rough overview of the parts in a docx file

The full standard is (I think) this one, which covers the technical definition of everything you can do in the standard.

The standard .NET library also includes DocumentFormat.OpenXml.Packaging which may help.

If someone come here looking for a solution to write a Word readable file from Unity, I have created this library to do this: GitHub - brunurd/RTFExporter: A C# library to generate .RTF text files from any string object data, stylized and ready for any text processor. No fancy dependencies or restrictive licenses.