— New online course!  Getting Started with Azure DevOps — Special launch price 50% off —

COMException When Trying to Access Any Member For an IIS DirectoryEntry

by

I’ve been playing around with writing a Custom Installer Actions for a VS2005 Web Application Deployment Project (aka Web Application Installer).  The most challenging thing after figuring out the syntax weirdnesses for Custom Installers was manipulating IIS from C#. 

There are a ton of blog entries out there on how to manipulate IIS from .NET but I was still having problems getting the code to work.  The big error that I kept getting was

System.Runtime.InteropServices.COMException: The system cannot find the path specified.

This error showed up whenever I tried to access any property or method on the DirectoryEntry object for the IIS directory. The error even showed up when I was in the debugger. 

The solution came from Saar Carmi’s blog post.  All the other posts out there got it MOSTLY right but Saar’s got this one little extra line in there:

folderRoot.RefreshCache();

That’s it.  That’s the line that makes EVERYTHING work.  Call RefreshCache() on the DirectoryEntry after you’ve created it and suddenly all those properties work.  (Thanks, Saar!)

Here’s a working piece of code piece of code:

public static DirectoryEntry FindDirectoryForPath(string appDirectory)
{
	string machineName = System.Environment.MachineName;
	string query;

	query = String.Format("IIS://{0}/w3svc", machineName);

	DirectoryEntry w3svc = new DirectoryEntry(query);

	DirectoryEntry appDirectoryEntry = null;

	foreach (DirectoryEntry webSite in w3svc.Children)
	{
		query = String.Format(
			"IIS://{0}/W3SVC/{1}/ROOT/{2}",
			machineName, webSite.Name, appDirectory);

		try
		{
			appDirectoryEntry = new DirectoryEntry(query);

			if (appDirectoryEntry != null)
			{
				appDirectoryEntry.RefreshCache();
				return appDirectoryEntry;
			}
		}
		catch (COMException)
		{

		}
		catch (Exception)
		{
			// not this one
		}
	}

	// couldn't find anything
	return null;
}

-Ben


One Response to "COMException When Trying to Access Any Member For an IIS DirectoryEntry"

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: