Microsoft.Office.Interop.Word process hangs

I am using a instance of Microsoft.Office.Interop.Word, I loop through each Paragraph and run a regex on each one looking for text.
The problem I am having is out of 50 documents 2 documents will not run through the code. I do not get any feedback, the WINWORD.EXE CPU is at 0% and it never ends.
This leaves a thread open on the code calling the Interop, until the WINWORD.EXE is killed.

I first would like to be able to set a maximum processing time, so this will close out correctly, even if it fails.


Any input or suggestions would be great.



EazyWorksAsked:
Who is Participating?
 
IshaJainConnect With a Mentor Commented:
U night not Managing the memory properly

try out with this code
try {
   / Intialize the Word application here.
    try {
        //try to open the document
        docRef = wordApp.Documents.Open(  ref file, ref missing, ref readOnly,
                                          ref missing, ref missing, ref missing,
                                          ref missing, ref missing, ref missing,
                                          ref missing, ref missing, ref isVisible,
                                          ref missing, ref missing, ref missing, ref missing);
        // some actions done like
        docRef.ActiveWindow.Selection.WholeStory();
        docRef.ActiveWindow.Selection.Copy();
        IDataObject data = Clipboard.GetDataObject();
        _rtbDoc.Paste();
        } catch (Exception ex) {
        throw ex;
    }
    finally{
        object boolObj = (object)false;
        docRef.Close(ref boolObj, ref boolObj, ref boolObj);
    }
    } catch (Exception ex) {
    throw ex;
}
finally{
    object boolObj = (object)false;
    wordApp.Quit(ref boolObj, ref boolObj, ref boolObj);
}
0
 
Chris BottomleyCommented:
I'm not strong in interop but can you provide the code ... perhaps something will stand out.

Chris
0
The new generation of project management tools

With monday.com’s project management tool, you can see what everyone on your team is working in a single glance. Its intuitive dashboards are customizable, so you can create systems that work for you.

 
EazyWorksAuthor Commented:
This is where I am at now.

I have two techniques for Merging Several Word documents into the same word document file.

What I want to do.
Open up and edit several word documents and save them into a folder to be merged.
Open and Merge all the word documents in this new folder to one new file and clear out the old files.

I have two functions below for merging the word documents.
I am currently using the "CombineDocuments"

Problem is I am using this for a web based application so if a warning comes up or something irregular with the word document it will hand up.

I want to set up the Error Handling as well as make this more robust.

I was also thinking of coping Paragraph Objects might be more efficient , but could not get it to copy all the formating as well.

Any input is appreciated. I am trying to wrap this up today.






public static void Merge(string[] filesToMerge, string outputFilename, bool insertPageBreaks, string documentTemplate)
        {
            object defaultTemplate = documentTemplate;
            object missing = System.Type.Missing;
            object pageBreak = Word.WdBreakType.wdPageBreak;
            object outputFile = outputFilename;

            // Create  a new Word application
            Word._Application wordApplication = new Word.Application();

            try
            {
                // Create a new file based on our template
                Word._Document wordDocument = wordApplication.Documents.Add(
                                              ref defaultTemplate
                                            , ref missing
                                            , ref missing
                                            , ref missing);

                // Make a Word selection object.
                Word.Selection selection = wordApplication.Selection;

                //Count the number of documents to insert;
                int documentCount = filesToMerge.Length;

                //A counter that signals that we shoudn't insert a page break at the end of document.
                int breakStop = 0;

                // Loop thru each of the Word documents
                foreach (string file in filesToMerge)
                {
                    breakStop++;
                    // Insert the files to our template
                    selection.InsertFile(
                                                file
                                            , ref missing
                                            , ref missing
                                            , ref missing
                                            , ref missing);

                    //Do we want page breaks added after each documents?
                    if (insertPageBreaks && breakStop != documentCount)
                    {
                        selection.InsertBreak(ref pageBreak);
                    }
                }

                // Save the document to it's output file.
                wordDocument.SaveAs(
                                ref outputFile
                            , ref missing
                            , ref missing
                            , ref missing
                            , ref missing
                            , ref missing
                            , ref missing
                            , ref missing
                            , ref missing
                            , ref missing
                            , ref missing
                            , ref missing
                            , ref missing
                            , ref missing
                            , ref missing
                            , ref missing);

                // Clean up!
                wordDocument = null;
            }
            catch (Exception ex)
            {
                //I didn't include a default error handler so i'm just throwing the error
                throw ex;
            }
            finally
            {
                // Finally, Close our Word application
                wordApplication.Quit(ref missing, ref missing, ref missing);
            }
        }
        public static void CombineDocuments(string[] filesToMerge, string outputFilename)
        {
            object wdPageBreak = 7;
            object wdStory = 6;
            object oMissing = System.Reflection.Missing.Value;
            object oFalse = false;
            object oTrue = true;

            Microsoft.Office.Interop.Word.Application WordApp = new Microsoft.Office.Interop.Word.Application();
            Microsoft.Office.Interop.Word.Document wDoc = WordApp.Documents.Add(ref oMissing, ref oMissing, ref oMissing, ref oMissing);

            //string[] wordFiles = Directory.GetFiles(fileDirectory, "*.doc");
            foreach (string file in filesToMerge)
            {
                wDoc.Application.Selection.Range.InsertFile(file, ref oMissing, ref oMissing, ref oMissing, ref oFalse);
                wDoc.Application.Selection.Range.InsertBreak(ref wdPageBreak);
                wDoc.Application.Selection.EndKey(ref wdStory, ref oMissing);

            }

            if (File.Exists(outputFilename))
                File.Delete(outputFilename);
            object combineDocNameObj = outputFilename;
            wDoc.SaveAs(ref combineDocNameObj, 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);
            WordApp.Quit(ref oTrue, ref oMissing, ref oMissing);
        }

Open in new window

0
 
Chris BottomleyConnect With a Mentor Commented:
The only thing I see at first sight is at the end of the sub:

            object combineDocNameObj = outputFilename;
            wDoc.SaveAs(ref combineDocNameObj, 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);
            WordApp.Quit(ref oTrue, ref oMissing, ref oMissing);

I would expect to see a close of wdoc immediately after the saveas.

Chris
0
 
EazyWorksAuthor Commented:
A couple questions,
How to prevent Dialogs from opening?
How to check to see if a file is locked by another word application ? is there a way to kill the other application?

Is there a Faster way, this code seems to run slow.
0
 
Chris BottomleyCommented:
When do the alerts appear? .. i.e. what activities do they imply?  Having saved the file ought to avoid such a prompt but in interop do you have an equivalent for displayaleterts which when set to false stops warnings.

In VBA you would use getobject to find an existing instance and createobject to create a new one and by testing the result of getobject you can see if there is an instance of the application and then scan through each document to see if the one you are looking for is there.

A faster way.  Absolutely cannot say since as I said i'm not interop competent.  However error handling does tend to slow things down dramitcally as does screen updates so avoiding errors and doing things without displayupdates is a potential improvement.

Chris
0
 
EazyWorksAuthor Commented:
One dialog is asking me if I want to save Normal.dot file.
Another will will come up saying file is being used by another process, this is after one of the WINWORD.exe processes has hung up.

This is all happening behind the seens the End user should not see anything and just get back a document at the end.

0
 
EazyWorksAuthor Commented:
How about a easy way to prevent a thread from running forever?
I would like the thread to time out if it cannot parse each file in more than 30 seconds.

0
 
IshaJainCommented:
if u want it in that way... then one thing u can do is...

start the process of reading in a new thread.
then do thread.join with the main thread specifying the timeout u require.

this will restrict the processing of the child thread to complete in the given timeout period.

I hope this will be helpful.

0
 
Chris BottomleyCommented:
Since it seems to be trying to save the template try ensuring it modifies the activedocument essentially replacing selection with wrddocument.range

Chris
                // Make a Word selection object. 
//                Word.Selection selection = wordApplication.Selection; 
 
                //Count the number of documents to insert; 
                int documentCount = filesToMerge.Length; 
 
                //A counter that signals that we shoudn't insert a page break at the end of document. 
                int breakStop = 0; 
 
                // Loop thru each of the Word documents 
                foreach (string file in filesToMerge) 
                { 
                    breakStop++; 
                    // Insert the files to our template 
                    wordDocument.range.InsertFile( 
                                                file 
                                            , ref missing 
                                            , ref missing 
                                            , ref missing 
                                            , ref missing); 
 
                    //Do we want page breaks added after each documents? 
                    if (insertPageBreaks && breakStop != documentCount) 
                    { 
                        wordDocument.range.InsertBreak(ref pageBreak); 
                    } 

Open in new window

0
 
Chris BottomleyCommented:
EazyWorks,

How goes it?

Chris
0
 
EazyWorksAuthor Commented:
I have some updates on this I will put up today or tomorrow.
I got it working relatively good and found out where I was running into issues as well.
Issue I am working on now is resetting of outline numbering when it merges in the new document. I want it as a Option in the Merge Code.

0
 
Chris BottomleyConnect With a Mentor Commented:
We can but see when you post the update ... be interesting if you highlight the changes because although unskilled with interop it'll be something else to take on board.

Chris
0
All Courses

From novice to tech pro — start learning today.