0

I have a simple code to write some text to a .docx file.

using (FileStream fs = new FileStream(filepath, FileMode.Open))
using (StreamWriter sw = new StreamWriter(fs, Encoding.Unicode))
{
     sw.WriteLine("something");
}

this writes to the file but when I try to open the file with MsWord it gives error

microsoft office cannot open this file because some parts are missing or invalid

but if I try to open the same file with wordpad or notepad, it opens and the text is written correctly. Why would this be?

Aditi
  • 1,188
  • 2
  • 16
  • 44
  • Not sure what is your question... Docx *is not text* file format - so it is reasonable that program that expects some other data in file is not able to handle your plain text. Please clarify what you are looking for (i.e. "how to create docx file with text" or "should I use .txt extension for my text file" or something else). – Alexei Levenkov Dec 23 '14 at 07:18

1 Answers1

0

.doc and .docx files actually are not just plain text files. They have a rather complex file format. So, when you put just plain text into a file and name it something.docx, Word will expect a properly formatted word file.

If you want to write a proper docx file, please refer to this question: How do I create the .docx document with Microsoft.Office.Interop.Word?

Community
  • 1
  • 1
Timo D
  • 1,723
  • 10
  • 16
  • Oh.. I suspected as much but thought there may be an easier way to get around the problem. Thanks for the prompt reply! :) – Aditi Dec 23 '14 at 07:20