как программно получить имя пула приложений для конкретного веб-сайта IIS6?С#
-
21-08-2019 - |
Вопрос
как получить имя пула приложений для конкретного веб-сайта IIS 6 программным способом с использованием C#
РЕДАКТИРОВАТЬ:Я уже использовал методы пространства имен DirectoryServices, но имя пула приложений не извлекается правильно, если оно не было явно задано с использованием того же кода.Это означает, что если вы добавите веб-сайт вручную с помощью диспетчера iis и установите пул приложений, эти коды не будут работать (он всегда будет возвращать DefaultAppPool), более того, когда я создаю приложение с помощью SharePoint и устанавливаю другой пул приложений, эти методы не работают.
Решение
Занятия в Пространство имен System.DirectoryServices поможет вам получить эту информацию.
Проверять эта статья Рика Страла для примера:
/// <summary>
/// Returns a list of all the Application Pools configured
/// </summary>
/// <returns></returns>
public ApplicationPool[] GetApplicationPools()
{
if (ServerType != WebServerTypes.IIS6 && ServerType != WebServerTypes.IIS7)
return null;
DirectoryEntry root = this.GetDirectoryEntry("IIS://" + this.DomainName + "/W3SVC/AppPools");
if (root == null)
return null;
List<ApplicationPool> Pools = new List<ApplicationPool>();
foreach (DirectoryEntry Entry in root.Children)
{
PropertyCollection Properties = Entry.Properties;
ApplicationPool Pool = new ApplicationPool();
Pool.Name = Entry.Name;
Pools.Add(Pool);
}
return Pools.ToArray();
}
/// <summary>
/// Create a new Application Pool and return an instance of the entry
/// </summary>
/// <param name="AppPoolName"></param>
/// <returns></returns>
public DirectoryEntry CreateApplicationPool(string AppPoolName)
{
if (this.ServerType != WebServerTypes.IIS6 && this.ServerType != WebServerTypes.IIS7)
return null;
DirectoryEntry root = this.GetDirectoryEntry("IIS://" + this.DomainName + "/W3SVC/AppPools");
if (root == null)
return null;
DirectoryEntry AppPool = root.Invoke("Create", "IIsApplicationPool", AppPoolName) as DirectoryEntry;
AppPool.CommitChanges();
return AppPool;
}
/// <summary>
/// Returns an instance of an Application Pool
/// </summary>
/// <param name="AppPoolName"></param>
/// <returns></returns>
public DirectoryEntry GetApplicationPool(string AppPoolName)
{
DirectoryEntry root = this.GetDirectoryEntry("IIS://" + this.DomainName + "/W3SVC/AppPools/" + AppPoolName);
return root;
}
/// <summary>
/// Retrieves an Adsi Node by its path. Abstracted for error handling
/// </summary>
/// <param name="Path">the ADSI path to retrieve: IIS://localhost/w3svc/root</param>
/// <returns>node or null</returns>
private DirectoryEntry GetDirectoryEntry(string Path)
{
DirectoryEntry root = null;
try
{
root = new DirectoryEntry(Path);
}
catch
{
this.SetError("Couldn't access node");
return null;
}
if (root == null)
{
this.SetError("Couldn't access node");
return null;
}
return root;
}
Другие советы
Я с тобой не согласен.Я написал тестовое приложение и получил от него правильное имя AppPool, даже если я установил AppPool вручную с помощью IIS Manager.
Чтобы убедиться, я проверил один раз, имя имя было в порядке;затем я открываю диспетчер IIS, меняю AppPool и запускаю iisreset
, и снова запустил тестовое приложение — полученное имя AppPool снова оказалось правильным.Я не знаю, как выглядел ваш код, но мой выглядит так:
using System;
using System.IO;
using System.DirectoryServices;
class Class
{
static void Main(string[] args)
{
DirectoryEntry entry = FindVirtualDirectory("<Server>", "Default Web Site", "<WantedVirtualDir>");
if (entry != null)
{
Console.WriteLine(entry.Properties["AppPoolId"].Value);
}
}
static DirectoryEntry FindVirtualDirectory(string server, string website, string virtualdir)
{
DirectoryEntry siteEntry = null;
DirectoryEntry rootEntry = null;
try
{
siteEntry = FindWebSite(server, website);
if (siteEntry == null)
{
return null;
}
rootEntry = siteEntry.Children.Find("ROOT", "IIsWebVirtualDir");
if (rootEntry == null)
{
return null;
}
return rootEntry.Children.Find(virtualdir, "IIsWebVirtualDir");
}
catch (DirectoryNotFoundException ex)
{
return null;
}
finally
{
if (siteEntry != null) siteEntry.Dispose();
if (rootEntry != null) rootEntry.Dispose();
}
}
static DirectoryEntry FindWebSite(string server, string friendlyName)
{
string path = String.Format("IIS://{0}/W3SVC", server);
using (DirectoryEntry w3svc = new DirectoryEntry(path))
{
foreach (DirectoryEntry entry in w3svc.Children)
{
if (entry.SchemaClassName == "IIsWebServer" &&
entry.Properties["ServerComment"].Value.Equals(friendlyName))
{
return entry;
}
}
}
return null;
}
}
Извините за мой паршивый английский.
Надеюсь, я помог.
Короче говоря, на ум приходят два способа сделать это.
Менее сложный способ — знать, что настройки IIS6 хранятся в MetaBase, которая представляет собой просто файл Xml:
C:\WINDOWS\system32\inetsrv\MetaBase.xml
Вы можете просто использовать Linq2Xml и проанализировать Xml в поисках имени или идентификатора сайта. Атрибут AppPoolId содержит имя AppPool.
Правильный способ — использовать System.DirectoryServices.