Thursday, May 26, 2011

Method to create Share folder in web server C#

public void CreateSharedFolder(string PhysicalPath, bool bFolderCreated)
{
try
{
int index = PhysicalPath.LastIndexOf("\\");
string AliasFolder = PhysicalPath.Substring(index + 1);
ManagementClass managementClass = new ManagementClass("Win32_Share");
// Create ManagementBaseObjects for in and out parameters
ManagementBaseObject inParams = managementClass.GetMethodParameters("Create");
ManagementBaseObject outParams;
// Set the input parameters
inParams["Name"] = AliasFolder;
inParams["Path"] = PhysicalPath;
inParams["Type"] = 0x0; // Disk Drive
// Invoke the method on the ManagementClass object
outParams = managementClass.InvokeMethod("Create", inParams, null);
// Check to see if the method invocation was successful
if ((uint)(outParams.Properties["ReturnValue"].Value) != 0)
{
if (bFolderCreated)
{
Directory.Delete(PhysicalPath, true);
}
throw new Exception("Unable to share directory as it is already in use.");
}
}
catch (Exception ex)
{
throw new Exception("Error :", ex);
}
}

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;
}