Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7445055
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 29, 20262026-05-29T11:43:38+00:00 2026-05-29T11:43:38+00:00

I’m trying to save an existing docx file on the desktop after I automate

  • 0

I’m trying to save an existing docx file on the desktop after I automate the word document in C#. I’m using the window form to execute my application. I’m able to save the document when there’s no same file name exists on the desktop. However when I try to save the same file name again it will give me this error message:

You cannot save while the file is in use by another process. Try
saving the file with a new name. (C:…\Desktop\TempWord.docx)

I read it in the Microsoft website I’m able to use SaveAs if there’s an existing file name, it will automatically override it.

I’m not too sure why this kind of message appears because I did not open any other word document at all when this program is being run.

I’m not too sure how to resolve this problem. Maybe I did something very stupid that I did not see 🙁


This is my code:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Reflection; 
using Microsoft.Office;
using Word = Microsoft.Office.Interop.Word;
using System.Runtime.InteropServices;


namespace TestWordAutoWithTemplate
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void butGenerate_Click(object sender, EventArgs e)
        {


            //OBJECT OF MISSING "NULL VALUE"
            Object oMissing = Missing.Value;

            //OBJECTS OF FALSE AND TRUE
            Object oTrue = true;
            Object oFalse = false;

            //CREATING OBJECTS OF WORD AND DOCUMENT
            Word.Application oWord = new Word.Application();
            Word.Document oWordDoc = new Word.Document();

            //SETTING THE VISIBILITY TO TRUE
            //oWord.Visible = true;

            //THE LOCATION OF THE TEMPLATE FILE ON THE MACHINE
            Object oTemplatePath = @"C:\Documents and Settings\YYC\Desktop\TestTemplate.dotx";

            //ADDING A NEW DOCUMENT FROM A TEMPLATE
            oWordDoc = oWord.Documents.Add(ref oTemplatePath, ref oMissing, ref oMissing, ref oMissing);
            int iTotalFields = 0; 

            foreach (Word.Field myMergeField in oWordDoc.Fields)
            {
                iTotalFields++;
                Word.Range rngFieldCode = myMergeField.Code;
                String fieldText = rngFieldCode.Text;

                // ONLY GETTING THE MAILMERGE FIELDS
                if (fieldText.StartsWith(" MERGEFIELD"))
                {
                    // THE TEXT COMES IN THE FORMAT OF
                    // MERGEFIELD  MyFieldName  \\* MERGEFORMAT
                    // THIS HAS TO BE EDITED TO GET ONLY THE FIELDNAME "MyFieldName"
                    Int32 endMerge = fieldText.IndexOf("\\");
                    Int32 fieldNameLength = fieldText.Length - endMerge;
                    String fieldName = fieldText.Substring(11, endMerge - 11);

                    // GIVES THE FIELDNAMES AS THE USER HAD ENTERED IN .dot FILE
                    fieldName = fieldName.Trim();

                    // **** FIELD REPLACEMENT IMPLEMENTATION GOES HERE ****//
                    // THE PROGRAMMER CAN HAVE HIS OWN IMPLEMENTATIONS HERE
                    if (fieldName == "Name")
                    {
                        myMergeField.Select();
                        //Check whether the control text is empty
                        if (txtName.Text == "")
                        {
                            oWord.Selection.TypeText(" ");
                        }
                        else
                        {
                            oWord.Selection.TypeText(txtName.Text); 
                        }
                    }
                    if (fieldName == "Address")
                    {
                        myMergeField.Select();
                        //Check whether the control text is empty
                        if (txtAddress.Text == "")
                        {
                            oWord.Selection.TypeText(" ");
                        }
                        else
                        {
                            oWord.Selection.TypeText(txtAddress.Text);
                        }
                    }

                    if (fieldName == "Age")
                    {
                        myMergeField.Select();
                        // check whether the control text is empty
                        if (txtAge.Text == "")
                        {
                            oWord.Selection.TypeText(" ");
                        }
                        else
                        {
                            oWord.Selection.TypeText(txtAge.Text); 
                        }
                    }

                    if (fieldName == "EAddress")
                    {
                        myMergeField.Select();
                        // check whether the control text is empty
                        if (txtEmail.Text == "")
                        {
                            oWord.Selection.TypeText(" ");
                        }
                        else
                        {
                            oWord.Selection.TypeText(txtEmail.Text);
                        }
                    }

                    if (fieldName == "Company")
                    {
                        myMergeField.Select();
                        // Check whether the control text is empty
                        if (txtCompany.Text == "")
                        {
                            oWord.Selection.TypeText(" ");
                        }
                        else
                        {
                            oWord.Selection.TypeText(txtCompany.Text);
                        }
                    }

                    if (fieldName == "TelNo")
                    {
                        myMergeField.Select();
                        // Check whether the control text is empty
                        if (txtTelephone.Text == "")
                        {
                            oWord.Selection.TypeText(" ");
                        }
                        else
                        {
                            oWord.Selection.TypeText(txtCompany.Text);
                        }
                    }

                    if (fieldName == "ODetails")
                    {
                        myMergeField.Select();
                        // Check whether the control text is empty
                        if (txtOther.Text == "")
                        {
                            oWord.Selection.TypeText(" ");
                        }
                        else
                        {
                            oWord.Selection.TypeText(txtOther.Text);
                        }
                    }

                }
            }

            oWord.Visible = false;

            //Marshal.ReleaseComObject(oWordDoc.Fields);
            //Marshal.ReleaseComObject(oWordDoc);
            //Marshal.;


            // If you want your document to be saved as docx
            Object savePath = @"C:\Documents and Settings\YYC\Desktop\TempWord.doc";
            //oWordDoc.Save();
            oWordDoc.SaveAs(ref savePath
                //, 
                //ref oMissing, 
                //ref oMissing, 
                //ref oMissing, 
                //ref oMissing, 
                //ref oMissing, 
                //ref oMissing, 
                //ref oMissing, 
                //ref oMissing, 
                //ref oMissing, 
                //ref oMissing, 
                //ref oMissing, 
                //ref oMissing, 
                //ref oMissing, 
                //ref oMissing, 
                //ref oMissing
               );



            // Close the Word document, but leave the Word application open.
            // doc has to be cast to type _Document so that it will find the 
            // correct Close method. 
            object doNotSaveChanges = Word.WdSaveOptions.wdDoNotSaveChanges;
            ((Word._Document)oWordDoc).Close(ref doNotSaveChanges, ref oMissing, ref oMissing);
            oWordDoc = null; 
            // word has to be case to type _Application so that it will find 
            // the correct Quit method. 
            ((Word._Application)oWord).Quit(ref doNotSaveChanges, ref oMissing, ref oMissing);
            oWord = null;
            GC.Collect();


        }
    }
}

I’m not too sure where I did it wrong.

Edit: I put the original code in.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-29T11:43:39+00:00Added an answer on May 29, 2026 at 11:43 am

    I made a method out of this so place this line of Code get rid of it in button generate and copy the new method below so your new code should look like this

    private void butGenerate_Click(object sender, EventArgs e)
    {
       SaveWordTemp2WordDoc();      
    }
    
    public void SaveWordTemp2WordDoc()
    {
        //OBJECT OF MISSING "NULL VALUE"
        object oMissing = System.Reflection.Missing.Value;
        //OBJECTS OF FALSE AND TRUE
        Object oTrue = true;
        Object oFalse = false;
    
        //CREATING OBJECTS OF WORD AND DOCUMENT
        Word.Application oWord = new Word.Application();
        Word.Document oWordDoc = new Word.Document();
    
        //SETTING THE VISIBILITY TO TRUE
        //oWord.Visible = true;
    
        //THE LOCATION OF THE TEMPLATE FILE ON THE MACHINE
        //Change the path to a path like c:\files\docTemps\
        Object oTemplatePath = @"C:\Documents and Settings\YYC\Desktop\TestTemplate.dotx";
    
        //ADDING A NEW DOCUMENT FROM A TEMPLATE
        oWordDoc = oWord.Documents.Add(ref oTemplatePath, ref oMissing, ref oMissing, ref oMissing);
        int iTotalFields = 0;
    
        foreach (Word.Field myMergeField in oWordDoc.Fields)
        {
            iTotalFields++;
            Word.Range rngFieldCode = myMergeField.Code;
            String fieldText = rngFieldCode.Text;
    
            // ONLY GETTING THE MAILMERGE FIELDS
            if (fieldText.StartsWith(" MERGEFIELD"))
            {
                // THE TEXT COMES IN THE FORMAT OF
                // MERGEFIELD  MyFieldName  \\* MERGEFORMAT
                // THIS HAS TO BE EDITED TO GET ONLY THE FIELDNAME "MyFieldName"
                Int32 endMerge = fieldText.IndexOf("\\");
                Int32 fieldNameLength = fieldText.Length - endMerge;
                String fieldName = fieldText.Substring(11, endMerge - 11);
    
                // GIVES THE FIELDNAMES AS THE USER HAD ENTERED IN .dot FILE
                fieldName = fieldName.Trim();
    
                // **** FIELD REPLACEMENT IMPLEMENTATION GOES HERE ****//
                // THE PROGRAMMER CAN HAVE HIS OWN IMPLEMENTATIONS HERE
                if (fieldName == "Name")
                {
                    myMergeField.Select();
                    //Check whether the control text is empty
                    if (txtName.Text == "")
                    {
                        oWord.Selection.TypeText(" ");
                    }
                    else
                    {
                        oWord.Selection.TypeText(txtName.Text);
                    }
                }
                if (fieldName == "Address")
                {
                    myMergeField.Select();
                    //Check whether the control text is empty
                    if (txtAddress.Text == "")
                    {
                        oWord.Selection.TypeText(" ");
                    }
                    else
                    {
                        oWord.Selection.TypeText(txtAddress.Text);
                    }
                }
    
                if (fieldName == "Age")
                {
                    myMergeField.Select();
                    // check whether the control text is empty
                    if (txtAge.Text == "")
                    {
                        oWord.Selection.TypeText(" ");
                    }
                    else
                    {
                        oWord.Selection.TypeText(txtAge.Text);
                    }
                }
    
                if (fieldName == "EAddress")
                {
                    myMergeField.Select();
                    // check whether the control text is empty
                    if (txtEmail.Text == "")
                    {
                        oWord.Selection.TypeText(" ");
                    }
                    else
                    {
                        oWord.Selection.TypeText(txtEmail.Text);
                    }
                }
    
                if (fieldName == "Company")
                {
                    myMergeField.Select();
                    // Check whether the control text is empty
                    if (txtCompany.Text == "")
                    {
                        oWord.Selection.TypeText(" ");
                    }
                    else
                    {
                        oWord.Selection.TypeText(txtCompany.Text);
                    }
                }
    
                if (fieldName == "TelNo")
                {
                    myMergeField.Select();
                    // Check whether the control text is empty
                    if (txtTelephone.Text == "")
                    {
                        oWord.Selection.TypeText(" ");
                    }
                    else
                    {
                        oWord.Selection.TypeText(txtCompany.Text);
                    }
                }
    
                if (fieldName == "ODetails")
                {
                    myMergeField.Select();
                    // Check whether the control text is empty
                    if (txtOther.Text == "")
                    {
                        oWord.Selection.TypeText(" ");
                    }
                    else
                    {
                        oWord.Selection.TypeText(txtOther.Text);
                    }
                }
    
            }
        }
    
        oWord.Visible = false;
    
        // If you want your document to be saved as docx
        //Change the file Path here to a path other than your desktop
        Object savePath = @"C:\Documents and Settings\YYC\Desktop\TempWord.doc";
        //oWordDoc.Save();
        oWordDoc.SaveAs(ref savePath,
            ref oMissing,
            ref oMissing,
            ref oMissing,
            ref oMissing,
            ref oMissing,
            ref oMissing,
            ref oMissing,
            ref oMissing,
            ref oMissing,
            ref oMissing,
            ref oMissing,
            ref oMissing,
            ref oMissing,
            ref oMissing,
            ref oMissing
           );
    
        // Close the Word document, but leave the Word application open.
        // doc has to be cast to type _Document so that it will find the 
        // correct Close method. 
        object doNotSaveChanges = Word.WdSaveOptions.wdDoNotSaveChanges;
        System.Runtime.InteropServices.Marshal.ReleaseComObject(oWordDoc);
        // word has to be case to type _Application so that it will find 
        // the correct Quit method. 
        ((Word._Application)oWord).Quit(ref doNotSaveChanges, ref oMissing, ref oMissing);
        System.Runtime.InteropServices.Marshal.ReleaseComObject(oWord);
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I am trying to find ID3V2 tags from MP3 file using jid3lib in Java.
I have just tried to save a simple *.rtf file with some websites and
I am trying to render a haml file in a javascript response like so:
We are using XSLT to translate a RIXML file to XML. Our RIXML contains
I'm trying to convert HTML to plain text. I get many &\#8217; &\#8220; etc.
I have a .ini file as follows: [playlist] numberofentries=2 File1=http://87.230.82.17:80 Title1=(#1 - 365/1400) Example
I am trying to understand how to use SyndicationItem to display feed which is
Basically, what I'm trying to create is a page of div tags, each has
I'm new to using the Perl treebuilder module for HTML parsing and can't figure
link Im having trouble converting the html entites into html characters, (&# 8217;) i

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.