C# WMI應用-結束Server端應用程序

  • 977
  • 0

摘要:C# WMI應用-結束Server端應用程序

最近在處理Excel相關的應用,相關範例可參考

http://www.dotblogs.com.tw/finalevil/archive/2008/09/28/5517.aspx

但發現如果利用ASP.NET去執行完Excel操作後,Excel應用程式會留在系統中,無法正常結束

這時候如果在多人環境中,我想Server的RAM一下子就會被吃光了。

 後來利用WMI + 暫時提升使用者權限的方式進行解決 (應該不是唯一解)

暫時提升使用者權限做法可參考:

http://blog.darkthread.net/post-2009-11-20-impersonate.aspx

http://support.microsoft.com/kb/306158/zh-tw

if (impersonateValidUser("Administrator", "localhost", "a123456"))
                {
                    ManagementScope theScope = new ManagementScope(String.Format("\\\\{0}\\root\\cimv2", HttpContext.Current.Server.MachineName));
                    theScope.Connect();
                    if (theScope.IsConnected)
                    {
                        ObjectQuery theQuery = new ObjectQuery("SELECT * FROM Win32_Process WHERE Name='EXCEL.EXE'");

                        ManagementObjectSearcher theSearcher = new ManagementObjectSearcher(theScope, theQuery);

                        ManagementObjectCollection theCollection = theSearcher.Get();

                        foreach (ManagementObject theCurObject in theCollection)
                        {

                            theCurObject.InvokeMethod("Terminate", null);

                        }
                    }
                }

結合這兩種用法後,不管使用者登入是誰,都可以輕鬆的在執行完Excel操作後。再將Server端的Excel結束掉

不過微軟不建議這樣子進行Office應用。

http://support.microsoft.com/kb/257757/zh-tw

不過沒辦法,先看看這專案Run的如何了