Thursday, May 26, 2011

Method to create Create IIS Virtual Directory in C#

private void CreateIISVirtualDirectory(string PhysicalPath)
{
try
{
string strVDPath = ConfigurationManager.AppSettings["VDPath"];

//Get the folder Name and assign it to alias for creating Virtual Directory

DirectoryInfo di = System.IO.Directory.GetParent(PhysicalPath);

PhysicalPath = di.Parent.FullName;

int index = PhysicalPath.LastIndexOf("\\");
string AliasFolder = PhysicalPath.Substring(index + 1);

DirectoryEntry de = new DirectoryEntry(GetWebSitePath() + "/ROOT/" + strVDPath);
DirectoryEntry newVDir = de.Children.Add(AliasFolder, "IIsWebVirtualDir");
newVDir.Properties["Path"][0] = PhysicalPath;
newVDir.Properties["AccessScript"][0] = true;
// These properties are necessary for an application to be created.
newVDir.Properties["AppFriendlyName"][0] = AliasFolder;
newVDir.CommitChanges();
}
catch (Exception ex)
{
Error.LogError(ex);
throw new Exception("Error :", ex);
}

}

private string GetWebSitePath()
{
string strPath = "";
string strWebSiteName = ConfigurationManager.AppSettings["HostedWebSite"];

DirectoryEntry w3svc = new DirectoryEntry("IIS://" + Environment.MachineName + "/w3svc");

foreach (DirectoryEntry de in w3svc.Children)
{
if (de.SchemaClassName == "IIsWebServer")
{
if (de.Properties["ServerComment"][0].ToString().ToUpper() == strWebSiteName.ToUpper())
{
strPath = de.Path;
break;
}
}
}
return strPath;
}

No comments: