Office操作出现进程在系统中不能关闭而出错, 另一个进程正在使用此文件

来源:互联网 发布:windows 8.1 WIFI 编辑:程序博客网 时间:2024/06/05 04:36

Microsoft.Office.Interop.Word._Application wordApp = new Microsoft.Office.Interop.Word.ApplicationClass();
                Microsoft.Office.Interop.Word._Document wordDoc = null;
                try
                {
                    //
打开Word文档对象 
                    wordDoc = wordApp.Documents.Open(ref filename, ref confirmConversions, ref readOnly, ref addToRecentFiles, ref passwordDocument, ref passwordTemplate, ref revert, ref writePasswordDocument, ref writePasswordTemplate, ref format, ref encoding, ref visible, ref openConflictDocument, ref openAndRepair, ref documentDirection, ref noEncodingDialog);
                    wordDoc.AcceptAllRevisions(); //
接收word中所有的修订
                    wordDoc.Save();//
保存
                    wordDoc.Close(ref missing, ref missing, ref missing);
                    wordApp.Application.Quit(ref saveOption, ref missing, ref missing);
                }
                catch { }
                finally
                {

                    //杀死打开的word进程
                    Process myProcess = new Process();
                    Process[] wordProcess = Process.GetProcessesByName("winword");
                    try
                    {
                        foreach (Process pro in wordProcess) //
这里是找到那些没有界面的Word进程
                        {
                           IntPtr ip= pro.MainWindowHandle;

                           string str = pro.MainWindowTitle; //发现程序中打开跟用户自己打开的区别就在这个属性
                            //
用户打开的str是文件的名称,程序中打开的就是空字符串
                            if (string.IsNullOrEmpty(str))
                            {
                                pro.Kill();
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        ex.ToString();
                    }
                }
            }