Go out of office with. Net (2)-close the office program with "clean"

Source: Internet
Author: User

In office. net (II)-use. net Access office programming interface, has introduced the use of office automation (office automation) technology, in.. Net Code directly accesses the office programming interface through office Pia. For example, in that article, we created a winforms program written in C #, started word directly in the program, and completed some work automatically by operating word with code, then, use the code to close the word.

 

When office automation is involved, you can start office by using custom code and perform operations on the office programming interface (whether in winforms or ASP. net Program), it is inevitable to encounter a problem, that is, how to "completely clean" to close the office program started by the Code. In fact, if the problem is not handled properly, the related office processes on the computer where the application is located will never be closed. If the application runs on a server, the consequences are even more serious, and may even result in server resource depletion and downtime.

 

I. Server scenario

 

Server-side office automation refers to accessing the office programming interface in a program running on the server, starting the Office program, and manipulating the Office to complete some automation operations. For example, an ASP. Net program or a Windows service is a server-side office automation scenario.

 

The first principle of server-side office automation is:Do not do this on the server sideOffice automcationOperation!Even the Office automcation operation on the server is not supported by Microsoft!

 

Yes, because it is very dangerous to perform the Office automcation operation on the server, the Office is not designed to run in unattended mode, that is, when the Office program is designed, by default, it is always assumed that a real user is sitting in front of the computer and interacts with the office program with the mouse and keyboard. If we use code to operate the Office, this assumption has actually been broken. What problems may be caused by breaking this assumption? The following lists some common problems:

 

(1) Since office always assumes that there is a real "user" currently using it, it may take the initiative to pop up some windows in some cases, requiring users to interact with it. For example, when an operation is not completed successfully or unexpected situations occur (for example, if the office needs to print but no printer is found, a file is saved, but a file with the same name is found ), the Office displays a mode window, prompting or asking the user for some information, which cannot be completely foreseen. Because our code cannot cancel this mode window, the current process will be completely blocked and the response will be lost.

(2) As a component running on the server, it must be designed in advance to be reused by multiple clients with as little overhead as possible, office is the opposite (Because office was originally designed to be used on the client). Every office application occupies a large amount of resources and is difficult to reuse.

(3) When you are using the office, you should often see that there is a "Preparing to install..." in the office ..." This is because the Office introduces an installation mode called "Install for the first time". Some components may be installed only when they are used for the first time. If this happens on the server side, the stability of the server is hard to be guaranteed.

(4) office always assumes that the current running environment is a real user's account identity, but office automation on the server sometimes uses some system accounts (such as network service and iuser_machine) in this case, the Office may fail to start normally and an error is thrown.

 

Therefore, do not perform office automation operations on the server unless you have! However, sometimes many things are not decided by programmers, so there are still a lot of people who are eager to bite their teeth and have to perform this operation on the server. If you have made up your mind and are confident to overcome all your difficulties, we will provide some suggestions on server-side office automation for your reference.

 

(1) try to prevent office from actively popping up some user interaction windows. For example, modifying the values of the asktoupdatelinks, alertbeforeoverwriting, displayalerts, and featureinstall attributes of the application can prevent the pop-up of some user interaction windows. In addition, it is important to take the initiative to defend against code writing. For example, before saving a file, first check whether a file with the same name already exists and before opening a file, you can also use the code to check whether the file exists.

(2) isolate the environment where the office is running. Do not directly create an office application instance in ASP. NET code. Otherwise, IIS may go down. Create an Independent Application to perform office automation operations, and then allow ASP. net programs to communicate with this independent application to indirectly access office functions. If conditions are met, it is even better to place a single application that performs office automation operations on a single server, so that if an exception occurs, you can directly restart the server without affecting the normal operation of the real business system. In addition, let the individual application run with a specific account (for example, a newly created and configured account that can interact with customers ).

(3) it is best to create a separate daemon to check whether the Office is not properly closed. If such a situation is found, directly close the corresponding process of the Office in the daemon.

 

2. close the office application in the code

 

When we are in. when you access the office programming interface in the. NET code, com InterOP creates a RCW (runtime callable wrapper, remote access package at runtime) under it to maintain reference to the office COM component. To make the office shut down normally, the key is to release the reference to the office-related objects in the code.

 

The following describes a variety of safeguard measures to enable the office application to be shut down normally. In some cases, you can use the simplest method. In some cases, you may need to combine multiple methods.

 

0. Remember to call the application. Quit () method.

 

Well, some programmers forget to call this method to exit the Office application. No matter which method is used to close the office, but forget to call this quit () method, nothing is useless.

 

1. Let garbage collection complete all work

 

Because. net Framework provides a garbage collector for automatic memory management, so in principle, as long as the reference to the office-related objects is released in our code (assign it null ), in this case, the garbage collection will eventually recycle this object. At that time, RCW will release the Office COM component to disable the office. To ensure the real-time disabling, we 'd better actively call garbage collection so that garbage collection can be performed immediately.

 

Microsoft. Office. InterOP. Word. Application wordapp = new Microsoft. Office. InterOP. Word. Application ();

// Perform some operations...

Object missing = type. missing;

Wordapp. Quit (ref missing, ref missing, ref missing );

Wordapp = NULL;

 

GC. Collect ();

GC. waitforpendingfinalizers ();

GC. Collect ();

GC. waitforpendingfinalizers ();

 

In most cases, this method can release our code to reference the Office and disable the office.

 

2. Call the system. runtime. interopservices. Marshal. releasecomobject () method.

 

The releasecomobject () method allows RCW to reduce a reference to the COM component and return the number of remaining references of RCW to the COM component after a reference is reduced. With a loop, we can let RCW remove all references to COM components.

 

First, create a separate method to release all references to an office-related object.

 

Private void releaseallref (Object OBJ)

{

Try

{

While (releasecomobject (OBJ)> 1 );

}

Finally

{

OBJ = NULL;
}

}

 

Then, call the releaseallref () method.

 

Microsoft. Office. InterOP. Word. Application wordapp = new Microsoft. Office. InterOP. Word. Application ();

// Perform some operations...

Object missing = type. missing;

Wordapp. Quit (ref missing, ref missing, ref missing );

 

Releaseallref (wordapp );

 

GC. Collect ();

GC. waitforpendingfinalizers ();

GC. Collect ();

GC. waitforpendingfinalizers ();

 

(3) declare and release each intermediate object variable separately

 

An intermediate object variable is an object obtained directly through the attribute of an object in the Code. It is directly used instead of being declared separately. For example:

 

Document Doc = wordapp. Documents. Add (...);

 

In the above Code, wordapp. the attributes are actually Microsoft. office. interOP. word. but the code above does not declare this object separately, but directly uses its add () method. If you want to declare it separately, you need to change it to the following:

 

Documents docs = wordapp. documents;

Document Doc = docs. Add (...);

 

After using these objects, use the methods described in (2) and release them one by one.

 

Doc. Close (...);

Releaseallref (DOC );

Releaseallref (DOCS );
Wordapp. Quit (...);

Releaseallref (wordapp );

 

Iii. Summary

 

The title of this article is "completely clean" Close office programs ". The reason why the" completely clean "modifier is enclosed in quotation marks is, the reason is that there is no permanent, 100% effective method to close the office program. Any code that performs office automation operations must be carefully tested and evaluated to minimize the impact on our programs.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.