Azure DevOps, Scrum, & .NET Software Leadership and Consulting Services

Free course! Predicting the Future, Estimating, and Running Your Projects with Flow Metrics

COMException When Trying to Access Any Member For an IIS DirectoryEntry


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

SUBSCRIBE TO THE BLOG


One response to “COMException When Trying to Access Any Member For an IIS DirectoryEntry”

  1. ben 10 oyun Avatar

    thanks for all admin
    süperrrr

Leave a Reply

Your email address will not be published. Required fields are marked *

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