title: when using open xml my file gets corrupt
body: <p>EDIT:
  the problem is now solved, it was that there is xml code which is named 'name' which i was accidentally changing. the solution was to have a obscure name in the docx file </p>
  
  <hr>
  
  <p>I am creating a program that modify a word document using open xml but every time the program runs the file gets corrupt and i don't know why or if there is any  way around it?</p>
  
  <p>i have had a look and one thing i saw was too make sure i had closed the connection but i tried that but i'm not sure if the connection is still opened</p>
  
  <p>edit:</p>
  
  <p>the output file says it corrupt but when the recovery in ms word run the files is as it should be</p>
  
  <p>from the images/code 
  the the original file is copied to temp.docx and has "name" in the file</p>
  
  <p>i require the program to replace "name" with another word.</p>
  
  <p>the program is semi working as it changes the value of the document however it is corrupting the document.</p>
  
  <p>link to photos: <a href="https://drive.google.com/open?id=0B130JvN0ZPPRODJpZWZENTNUX0E" rel="nofollow">https://drive.google.com/open?id=0B130JvN0ZPPRODJpZWZENTNUX0E</a> </p>
  
  <p>CODE</p>
  
  <pre><code>private void gen_btn_Click(object sender, EventArgs e)
      {
  
          if (System.IO.File.Exists(@"C:\invoices\temp.docx"))
          {
              // Use a try block to catch IOExceptions, to 
              // handle the case of the file already being 
              // opened by another process. 
              try
              {
                  System.IO.File.Delete(@"C:\invoices\temp.docx");
              }
              catch (System.IO.IOException exception)
              {
                  Console.WriteLine(exception.Message);
                  return;
              }
          }
          File.Copy(@"C:\invoices\template.docx", @"C:\invoices\temp.docx");
          SearchAndReplace("name", "asdsadsadasdasdas");
      }
  
     public static void SearchAndReplace(string wordtoreplace, string replace)
  
      {
          using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(@"C:\invoices\temp.docx", true))
          {
              string docText = null;
              using (StreamReader sr = new StreamReader(wordDoc.MainDocumentPart.GetStream()))
              {
                  docText = sr.ReadToEnd();
              }
  
              //Regex regexText = new Regex(wordtoreplace);
              docText = docText.Replace(wordtoreplace, replace);
  
              using (StreamWriter sw = new StreamWriter(wordDoc.MainDocumentPart.GetStream(FileMode.Create)))
              {
                  sw.Write(docText);
  
              }
              wordDoc.Close();
  
  
          }
      }
  </code></pre>