Wednesday, October 18, 2006

IIS : Getting Physical Path for Virtual Directory in .NET

Here is a C# code sample of how to use System.DirectoryServices in .NET to get the physical path for IIS virtual directory.


class Class1
{
[STAThread]
static void Main(string[] args)
{
string serverComment = "Default Web Site";
string iisHost = "IIS://LocalHost";
string siteName = GetIISSiteName(iisHost, serverComment);


Console.WriteLine(siteName);
if(siteName.Equals(String.Empty))
{
Console.WriteLine("Site not found.");
}
else
{
// Get the physical path for http://localhost/testemail
string path = GetVirtualDirPath(iisHost, siteName, "testemail");

if(path.Equals(String.Empty))
Console.WriteLine("VD not found.");
else
Console.WriteLine(path);
}

Console.WriteLine("done");
Console.ReadLine();
}


static string GetIISSiteName(string iisHost, string serverComment)
{
string adsiPath = iisHost + "/W3SVC";
DirectoryEntry entry = new DirectoryEntry(adsiPath);
foreach (DirectoryEntry site in entry.Children)
{
if (site.SchemaClassName == "IIsWebServer" &&
site.Properties["ServerComment"].Value
.ToString().Equals(serverComment))
{
return site.Name;
}
}

return "";
}


static string GetVirtualDirPath(string iisHost,
string siteName, string vdName)
{
string adsiPath = iisHost + "/W3SVC/" + siteName + "/Root/" + vdName;

try
{
DirectoryEntry entry = new DirectoryEntry(adsiPath);
return entry.Properties["Path"].Value.ToString();
}
catch(Exception ex)
{
// If Virtual Directory is not found,
// it will throw exception.
return "";
}

return "";
}
}

Labels:

2 Comments:

At 7:07 PM, Anonymous Anonymous said...

Hi mister, thanks.

Now, How can I get all web sites installed in IIS ??

Thanks.

enrique.prados@a-e.es

 
At 7:40 PM, Blogger Anand said...

This does not work in win2008 server machines. what should be changed for win2008 machines?

 

Post a Comment

<< Home