title: Sitecore Clear Cache Programmatically
body: <p>I am trying to publish programmatically in Sitecore. Publishing works fine. But doing so  programmatically doesn't clear the sitecore cache. What is the best way to clear the cache programmatically?</p>
  
  <p>I am trying to use the webservice that comes with the staging module. But I am getting a Bad request exception(<strong><em>Exception: The remote server returned an unexpected response: (400) Bad Request.</em></strong>). I tried to increase the service receivetimeout and sendtimeout on the client side config file but that didn't fix the problem. Any pointers would be greatly appreciated?</p>
  
  <p>I am using the following code:</p>
  
  
  
  <pre class="lang-cs prettyprint-override"><code>CacheClearService.StagingWebServiceSoapClient client = new CacheClearService.StagingWebServiceSoapClient();
  CacheClearService.StagingCredentials credentials = new CacheClearService.StagingCredentials();
  
  credentials.Username = "sitecore\adminuser";
  credentials.Password = "***********";
  credentials.isEncrypted = false;
  
  bool s = client.ClearCache(true, dt, credentials);
  </code></pre>
  
  <p>I am using following code to do publish.</p>
  
  <pre class="lang-cs prettyprint-override"><code> Database master = Sitecore.Configuration.Factory.GetDatabase("master");
   Database web = Sitecore.Configuration.Factory.GetDatabase("web");
  
   string userName = "default\adminuser";
  
   Sitecore.Security.Accounts.User user = Sitecore.Security.Accounts.User.FromName(userName, true);
  
   user.RuntimeSettings.IsAdministrator = true;
  
   using (new Sitecore.Security.Accounts.UserSwitcher(user))
   {
  
       Sitecore.Publishing.PublishOptions options = new Sitecore.Publishing.PublishOptions(master, web,
       Sitecore.Publishing.PublishMode.Full, Sitecore.Data.Managers.LanguageManager.DefaultLanguage, DateTime.Now);
  
       options.RootItem = master.Items["/sitecore/content/"];
       options.Deep = true;
       options.CompareRevisions = true;
       options.RepublishAll = true;
       options.FromDate = DateTime.Now.AddMonths(-1);
  
       Sitecore.Publishing.Publisher publisher = new Sitecore.Publishing.Publisher(options);
       publisher.Publish();
    }
  </code></pre>