title: How to access IIS through C# Console Application
body: <p>I am trying to access my server's IIS pool in order to recycle it through C# code.</p>
  
  <p>This is my code:</p>
  
  <pre><code>static void Main(string[] args)
  {
      try
      {
          string sMachine = "MyHostName";
          string sAppPool = "MyAppPoolName";
  
          string sPath = "IIS://" + sMachine + "/W3SVC/AppPools/" + sAppPool;
          Console.WriteLine(sPath);
  
          DirectoryEntry w3svc = new DirectoryEntry(sPath, "MyUserName", "MyPassword");
          w3svc.Invoke("Recycle", null);
  
          Console.WriteLine("Application pool recycled");
      }
      catch (Exception ex)
      {
          Console.WriteLine("Error: " + ex.Message);
      }
  }
  </code></pre>
  
  <p>I changed the sMachine / sAppPool / UserName, Password, but in my code I send them with the real data.</p>
  
  <p>When I run it on my VM I get a message </p>
  
  <pre><code>Error: Unknown Exception
  </code></pre>
  
  <p>I think it occurs because the permission so I run it with the administrator of the VM and run as administrator the exe file, but still I get the same error.</p>
  
  <p>How could I access the IIS?</p>
  
  <p>Thanks in advance.</p>