Hello here is my csharp code to get all sites from the IIS Server
List<IISObject> iisSiteList = new List<IISObject>();
ServerManager serverMgr = new ServerManager();
SiteCollection sitecollection = serverMgr.Sites;
try
{
foreach (var site in sitecollection)
{
string SiteState = site.State.ToString();
if (site.Name != "Default Web Site")
{
IISObject issObject = new IISObject() { Name = site.Name, SiteId = site.Id, State = SiteState };
iisSiteList.Add(issObject);
}
}
return iisSiteList;
}
catch (Exception e)
{
return e.Message.ToString();
}
The above code giving me the following error
('The object identifier does not represent a valid object. (Exception from ' 'HRESULT: 0x800710D8)')
The reason of this error is one of the site has unknown state, so if I simply comment this line string SiteState = site.State.ToString(); then it start working.
Now I need help that how I can validate ObjectState before assign it to a variable. I tried this
if (site.State)
{
string SiteState = site.State.toString();
}
else
{
string SiteState = "unknown"
}
Then Visual Studio showing this
CS0029: Cannot implicitly convert type 'Microsfot.Web.Administration.ObjectState' to 'bool'
Now would you please help me how to fix this
Microsoft.Web.Administration ObjectState is an enum type, you need to check it like
site.State != ObjectState.Unknown, you can use the following example as a reference: