Tuesday, May 15, 2012

Read IIS SessionTimeout of Virtual Directory

class Program
    {
        static void Main(string[] args)
        {
            string urlSuffix = "";

            while(true)
            {
                Console.WriteLine("Please enter domain foldername(iis)/exit:");
                urlSuffix = Console.ReadLine();
                if (urlSuffix == "")
                {
                    urlSuffix = "ussi";
                }

                if (urlSuffix == "exit" ||urlSuffix == "Exit")
                {
                    break;
                }
                // Locals
                int iRet = 20;
                DirectoryEntry deVirDir = null;
                string vdPath = null;
                IEnumerator childs = null;
                bool gotVD = false;
                bool found = false;

                try
                {
                    //vdPath = "IIS://localhost" + System.Web.Hosting.HostingEnvironment.ApplicationID.Remove(0, 3);// Remove "/LM"
                    vdPath = "IIS://localhost/w3svc/1/root/" + urlSuffix;
                    deVirDir = new DirectoryEntry(vdPath);

                    try
                    {
                        childs = deVirDir.Children.GetEnumerator();
                        gotVD = true;
                    }
                    catch
                    {
                        // if application details are not available, check out root details
                        deVirDir = new DirectoryEntry("IIS://localhost/W3SVC");
                        childs = deVirDir.Children.GetEnumerator();
                    }

                    while (childs.MoveNext() && !found)
                    {
                        DirectoryEntry deApp = (DirectoryEntry)childs.Current;

                        if (deApp.SchemaClassName == (gotVD ? "IIsWebDirectory" : "IIsWebServer"))
                        {
                            PropertyValueCollection pvcAspSTO = deApp.Properties["AspSessionTimeout"];
                            iRet = (int)pvcAspSTO[0];// only one value
                            found = true;
                        }
                    }
                }
                catch
                {
                    iRet = 20;
                }
                Console.Write("Timeout:" + iRet.ToString()+"\n");
            } 
        }
    }