How to invalidate CloudFront cache programatically

To control the versions of files that are served from your distribution, you can either invalidate files or give them versioned file names.
In this article will show how you can invalidate CloudFront cache programatically through c# code. 

Invalidate CloudFront by folder

 
  public static bool InvalidateFiles(string folderName, string cloudFrontDistributionId)  
   {  
     try  
     {  
       Amazon.CloudFront.AmazonCloudFrontClient oClient = new Amazon.CloudFront.AmazonCloudFrontClient(Amazon.RegionEndpoint.APSoutheast1);  
       CreateInvalidationRequest oRequest = new CreateInvalidationRequest();  
       oRequest.DistributionId = cloudFrontDistributionId;  
       oRequest.InvalidationBatch = new InvalidationBatch  
       {  
         CallerReference = DateTime.Now.Ticks.ToString(),  
         Paths = new Paths  
         {  
           Items = new List<string>() { "/" + folderName + "/*" },  
           Quantity = 1  
         }  
       };  
       CreateInvalidationResponse oResponse = oClient.CreateInvalidation(oRequest);  
       oClient.Dispose();  
     }  
     catch  
     {  
       return false;  
     }  
     return true;  
   }  

Invalidate CloudFront specific file

 
 public static bool InvalidateCustomPath(string pathName, string cloudFrontDistributionId)  
   {  
     try  
     {  
       Amazon.CloudFront.AmazonCloudFrontClient oClient = new Amazon.CloudFront.AmazonCloudFrontClient(Amazon.RegionEndpoint.APSoutheast1);  
       CreateInvalidationRequest oRequest = new CreateInvalidationRequest();  
       oRequest.DistributionId = cloudFrontDistributionId;  
       oRequest.InvalidationBatch = new InvalidationBatch  
       {  
         CallerReference = DateTime.Now.Ticks.ToString(),  
         Paths = new Paths  
         {  
           Items = new List<string>() { pathName },  
           Quantity = 1  
         }  
       };  
       CreateInvalidationResponse oResponse = oClient.CreateInvalidation(oRequest);  
       oClient.Dispose();  
     }  
     catch  
     {  
       return false;  
     }  
     return true;  
   }  

 

 

 Back to listing