How to Create a Virtual Directory using C#?

  • Thread starter Thread starter Smitha Nataraj
  • Start date Start date
S

Smitha Nataraj

Hello,

I need to create a Virtual Directory in C#.

Pls let me know if you have any hints regarding this..

Thanks,
Smitha
 
I need to create a Virtual directory in IIS i.e. I need to create a web
application on the IIS server from my .NET application.

This can be done using DirectoryServices in .NET. But I am facing some
problems. The directory entry is done but I cannot see it in IIS manager nor
does the application exist. But, if we try to create it again with the same
name, it says already exists.

Pls let me know if you have any hint...

Thanks!
Smitha
 
I used this in the past...
/// <summary>
/// Create a new Virtual Directory within IIS
/// </summary>
/// <param name="ServerId">The ID of the Server within IIS</param>
/// <param name="VirtualDirName">IIS Name of the new Virtual Directory</param>
/// <param name="Path">Physical Path to the new Virtual Directory</param>
/// <param name="AccessScript"></param>
/// <param name="CreatePhysicalFolder">Create the folder on the file system</param>
public static bool CreateNewVirtualDirectory(int ServerId, string VirtualDirName, string Path, bool AccessScript, bool CreatePhysicalFolder)
{
DirectoryEntry Parent = new DirectoryEntry(@"IIS://localhost/W3SVC/" + ServerId.ToString() + "/Root");
DirectoryEntry NewVirtualDir;
NewVirtualDir = Parent.Children.Add(VirtualDirName, "IIsWebVirtualDir");
NewVirtualDir.Properties["Path"][0] = Path;
NewVirtualDir.Properties["AccessScript"][0] = AccessScript;
NewVirtualDir.Properties["AppFriendlyName"][0] = VirtualDirName;
NewVirtualDir.Properties["AppPoolId"][0] = "DefaultAppPool";
NewVirtualDir.Properties["AppRoot"][0] = "/LM/W3SVC/" + ServerId.ToString() + "/Root/" + VirtualDirName;
NewVirtualDir.Properties["AppIsolated"][0] = 2;
NewVirtualDir.CommitChanges();
if(CreatePhysicalFolder)
{
if(!Directory.Exists(Path))
{
Directory.CreateDirectory(Path);
return true;
}
}
else
{
return true;
}
return true;
}

(Error checking / catching has been stripped from this example...)
 
Back
Top