[.NET]修改IIS Web執行的.NET版本,由2.0改成4.0
前言
使用InstallShield來包裝Web AP很方便,但是如果Web AP中包含.NET 2.0及.NET 4.0的版本時,裝起來後,會導致IIS的Application Pool錯亂,所以只好全都先使用.NET 2.0,針對需要用.NET 4.0的AP,自已寫程式來改.NET的版本!
實作
因為修改IIS Web執行的.NET版本,IIS6與IIS7的作法不同,IIS6是改在Web AP虛擬目錄的屬性之中,而IIS7則是要修改Web AP所使用的Application Pool。
要區分IIS的版本,請參考「Using Managed Code to Detect if IIS is Installed and ASP/ASP.NET is Registered」。
因為有使用到DirectoryServices及ManagementObject,所以使用的專案要加入System.DirectoryServices及System.Management參加。
//要加入 System.DirectoryServices 參考using System.DirectoryServices;using System.Collections;//要加入 System.Management 參考using System.Management;
IIS6
要俢改虛擬目錄中ASP.NET Tab中的.NET版本,使用System.DirectoryServices來修改ScriptMaps。
MessageBox.Show("目前系統是IIS6");//IIS6 所以要修改虛擬目錄的ScriptMaps值//參考:http://blog.sina.com.cn/s/blog_3ef2a82a0100dq8d.htmlDirectoryEntry sited = new DirectoryEntry(@"IIS://localhost/w3svc/1/Root");DirectoryEntry webFolderEntry = null;foreach (DirectoryEntry child in sited.Children){if (child.Name.ToLower() == txtWebFolderName.Text.ToLower().Trim()){//找到了webFolderEntry = child;break;}}//ScriptMaps原有屬性值object[] allValues = (Object[])webFolderEntry.InvokeGet("ScriptMaps");//存放ScriptMaps修改後的值object[] newValues = new object[allValues.Length];string oldVersion = "v2.0.50727";string newVersion = "v4.0.30319";//如果ScriptMaps中的值有v2.0.50727的話,就改成v4.0.30319for (int i = 0; i < allValues.Length; i++){if (allValues[i] is string){string temp = allValues[i] as string;if (temp.Contains(oldVersion)){newValues[i] = temp.Replace(oldVersion, newVersion);}else{newValues[i] = allValues[i];}}else{newValues[i] = allValues[i];}}//ScriptMaps更改属性值webFolderEntry.Properties["ScriptMaps"].Value = newValues;webFolderEntry.CommitChanges();
IIS7
要修改使用的Application Pool的版本,使用WMI來修改ManagedRuntimeVersion。
MessageBox.Show("目前系統非IIS6");//非IIS6 所以應該是IIS7,要修改Application Pool的版本//參考:http://hi.baidu.com/yandavid/blog/item/89242fd1462994209b502787.htmlManagementObject appPool = new ManagementObject(string.Format(@"\\.\root\WebAdministration:ApplicationPool.Name='{0}'", txtApplicationPoolName.Text.Trim() ));appPool.SetPropertyValue("ManagedRuntimeVersion", "v4.0");appPool.Put();
參考資料
Using Managed Code to Detect if IIS is Installed and ASP/ASP.NET is Registered
C#利用DirectoryEntry 类更新IIS ScriptMaps属性
IIS 7 管理 API API Microsoft.Web.Administration 经测试:不支持IIS Express
原始碼
Hi,
亂馬客Blog已移到了 「亂馬客 : Re:從零開始的軟體開發生活」
請大家繼續支持 ^_^

