Re: Настройка ISS и веб-директорий программно
От: Pavel_Agurov Россия  
Дата: 12.09.06 12:16
Оценка: 84 (4)
Примерно вот такой класс:


using System;
using System.DirectoryServices;

namespace IISTest
{
    /// <summary>
    /// Summary description for IISManager.
    /// </summary>
    public class IISManager
    {
        /// <summary>
        ///        Constructor
        /// </summary>
        
        /// <summary>
        ///        Default constructor uses localhost as default server
        /// </summary>
        public IISManager()
        {
             
        }
    
        //
        // Determine version of IIS
        //
        private bool IsNTIIS(string serverName)
        {
            bool IISUnderNT;
            System.DirectoryServices.DirectoryEntry IISSchema;

            IISSchema = new  System.DirectoryServices.DirectoryEntry("IIS://" +serverName +"/Schema/AppIsolated");
            if  (IISSchema.Properties["Syntax"].Value.ToString().ToUpper() == "BOOLEAN")
                IISUnderNT = true;
            else
                IISUnderNT = false;
            IISSchema.Dispose();
            return(IISUnderNT);
        }
    
 
        public string CreateVDir(string VDirName, string Path, bool  RootDir, bool chkRead,bool chkWrite, bool chkExecute, bool chkScript, bool chkAuth,int webSiteNum, string serverName)
        {
            string sRet=String.Empty;
            System.DirectoryServices.DirectoryEntry IISAdmin;
            System.DirectoryServices.DirectoryEntry VDir;

            bool IISUnderNT = IsNTIIS(serverName);

            //
            // Get the admin object
            //
            IISAdmin = new  System.DirectoryServices.DirectoryEntry("IIS://" +serverName +"/W3SVC/" + webSiteNum + "/Root");

            //
            // If we're not creating a root directory
            //
            if (!RootDir)
            {
                //
                // If the virtual directory already exists then delete it
                //
             
                foreach(System.DirectoryServices.DirectoryEntry v in IISAdmin.Children)
                {
                    if (v.Name == VDirName)
                    {
                        // Delete the specified virtual directory if it already exists
                        try
                        {
                            IISAdmin.Invoke("Delete", new string [] { v.SchemaClassName, VDirName });
                            IISAdmin.CommitChanges();
                        }
                        catch(Exception ex)
                        {
                            sRet+=ex.Message;
                        }
                    }
                }
            }     

            //
            // Create the virtual directory
            //
            if (!RootDir)
            {
                VDir = IISAdmin.Children.Add(VDirName, "IIsWebVirtualDir");
            }
            else
            {
                VDir = IISAdmin;
            }

            //
            // Setup the VDir
            //
            VDir.Properties["AccessRead"][0] = chkRead;
            VDir.Properties["AccessExecute"][0] = chkExecute;
            VDir.Properties["AccessWrite"][0] = chkWrite;
            VDir.Properties["AccessScript"][0] = chkScript;
            VDir.Properties["AuthAnonymous"][0] = false;
            VDir.Properties["AuthNTLM"][0] = chkAuth;
            VDir.Properties["EnableDefaultDoc"][0] = true;
            VDir.Properties["EnableDirBrowsing"][0] = false;
            VDir.Properties["DefaultDoc"][0] = true;
            VDir.Properties["Path"][0] = Path;
            VDir.Properties["DefaultDoc"][0] = "default.aspx";

            //
            // NT doesn't support this property
            //
            if (!IISUnderNT)
            {
                VDir.Properties["AspEnableParentPaths"][0] = true;
            }

            //
            // Set the changes  
            //
            VDir.CommitChanges();

            //
            // Make it a web application
            //
            if (IISUnderNT)
            {
                VDir.Invoke("AppCreate", false);
            }
            else
            {
                VDir.Invoke("AppCreate", 1);
            }

            sRet+= "VRoot " +VDirName + " created!";
            return sRet;
        }

        public string UpdateVDirPath(string serverName, int webSiteNum, string VDirName, string Path)
        {
            System.DirectoryServices.DirectoryEntry IISAdmin;

            bool IISUnderNT = IsNTIIS(serverName);

            //
            // Get the admin object
            //
            IISAdmin = new  System.DirectoryServices.DirectoryEntry("IIS://" +serverName +"/W3SVC/" + webSiteNum + "/Root");

         
            foreach(System.DirectoryServices.DirectoryEntry VDir in IISAdmin.Children)
            {
                if (VDir.Name == VDirName)
                {
                    // Update the specified virtual directory if it found
                    try
                    {
                        VDir.Properties["Path"][0] = Path;
                        VDir.CommitChanges();
                        return("Ok");
                    }
                    catch(Exception ex)
                    {
                        return(ex.Message);
                    }
                }
            }
            return("Not found.");
        }

        public string DeleteVDir(string VDirName, int webSiteNum, string serverName)
        {
            string sRet = String.Empty;
            System.DirectoryServices.DirectoryEntry IISAdmin;

            bool IISUnderNT = IsNTIIS(serverName);

            //
            // Get the admin object
            //
            IISAdmin = new  System.DirectoryServices.DirectoryEntry("IIS://" +serverName +"/W3SVC/" + webSiteNum + "/Root");

            //
            // If the virtual directory exists then delete it
            //
             
            foreach(System.DirectoryServices.DirectoryEntry v in IISAdmin.Children)
            {
                if (v.Name == VDirName)
                {
                    // Delete the specified virtual directory if it already exists
                    try
                    {
                        IISAdmin.Invoke("Delete", new string [] { v.SchemaClassName, VDirName });
                        IISAdmin.CommitChanges();
                    }
                    catch(Exception ex)
                    {
                        sRet+=ex.Message;
                    }
                }
            }
            sRet+= "VRoot " +VDirName + " deleted!";
            return sRet;
        }
        


        #region Properties
        public string ServerName
        {
            get
            {
                return _serverName;
            }
            set
            {
                _serverName = value;
            }
        }
        #endregion
        
        public static string VirDirSchemaName = "IIsWebVirtualDir";
        
        #region Private Members    
        private string _serverName;
    
        #endregion
    }


}



Использую так:


IISTest.IISManager man = new IISTest.IISManager();
string result = man.UpdateVDirPath(host, 1, dirname, path + dirname);
Настройка ISS и веб-директорий программно
От: GoldbergCAA  
Дата: 12.09.06 10:16
Оценка:
Здравствуйте, жители RSDN'а и вчастности обитатели форума.

У меня появилась проблема: Мне требуется программным методом настроить веб-директорию в ISS 6.0, так что бы её обрабатывал именно ASP.NET 2.0.

Заранее благодарен всем ответам... Может хотя бы подскажите где можно покапать... А то замучал гугл уже этим вопросом, а нашёл по этому поводу только на китайском
Настройка ISS и веб-директорий программно
От: Аноним  
Дата: 12.09.06 10:53
Оценка:
См. WMI начинающиеся с IIS*
Все должно быть просто, очень просто, настолько просто — насколько это возможно!
Мой блог Возможно на твой вопрос уже есть ответ? FAQ


данное сообщение получено с www.gotdotnet.ru
ссылка на оригинальное сообщение
Re: Настройка ISS и веб-директорий программно
От: GoldbergCAA  
Дата: 12.09.06 11:19
Оценка:
Здравствуйте, Евгений Веприков, Вы писали:

ЕВ>См. WMI начинающиеся с IIS*


Что — то не могу там найти по поводу настройки ASP.NET у веб — директории... Мож кто — нибудь сталкивался с данной проблемой... Вообще мне это требуется для написания инсталятора. Для написания используется MSVS 2005... Инсталятор должен создать веб приложение, которое будет работать на ASP.NET 2.0
Re[2]: Настройка ISS и веб-директорий программно
От: GoldbergCAA  
Дата: 12.09.06 12:02
Оценка:
Всё что там нарыл, это возможность изменения свойства ScriptMaps. Но может есть другой метод?
Re[2]: Настройка ISS и веб-директорий программно
От: GoldbergCAA  
Дата: 13.09.06 10:05
Оценка:
Здравствуйте, Pavel_Agurov, Вы писали:

P_A>Примерно вот такой класс:


А где в данном классе ты устанавливаешь значение какой ASP.NET будет обрабатывать веб-папку и к какому Application Pool'у она относиться? Что — то не нашёл...
Re[3]: Настройка ISS и веб-директорий программно
От: Pavel_Agurov Россия  
Дата: 13.09.06 10:27
Оценка:
здесь
на крайний случай здесь
Re[4]: Настройка ISS и веб-директорий программно
От: GoldbergCAA  
Дата: 13.09.06 12:32
Оценка:
Здравствуйте, Pavel_Agurov, Вы писали:

P_A>здесь

P_A>на крайний случай здесь

Спасибо, особенно за последнюю ссылку )) Покапаюсь там, мож что — нибудь полезное найду...
 
Подождите ...
Wait...
Пока на собственное сообщение не было ответов, его можно удалить.