Advertisement
A_GUES

C# AdBlocker

May 30th, 2023 (edited)
165
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.62 KB | None | 0 0
  1. using System;
  2. using System.IO;
  3. using System.Text.RegularExpressions;
  4.  
  5. class AdBlocker
  6. {
  7.     private Regex adRegex;
  8.  
  9.     public AdBlocker()
  10.     {
  11.         // Load the list of ad domains from a file
  12.         LoadAdDomains("ad_domains.txt");
  13.     }
  14.  
  15.     public void LoadAdDomains(string filePath)
  16.     {
  17.         try
  18.         {
  19.             // Read the file containing ad domains
  20.             string[] domains = File.ReadAllLines(filePath);
  21.  
  22.             // Create a regular expression pattern to match ad domains
  23.             string pattern = string.Format(@"(^|\.)({0})$", string.Join("|", domains));
  24.  
  25.             // Compile the regular expression
  26.             adRegex = new Regex(pattern, RegexOptions.Compiled | RegexOptions.IgnoreCase);
  27.         }
  28.         catch (Exception ex)
  29.         {
  30.             Console.WriteLine("Failed to load ad domains: " + ex.Message);
  31.         }
  32.     }
  33.  
  34.     public bool IsAd(string url)
  35.     {
  36.         // Check if the URL matches the ad domain pattern
  37.         return adRegex.IsMatch(url);
  38.     }
  39. }
  40.  
  41. class Program
  42. {
  43.     static void Main()
  44.     {
  45.         // Create an instance of the AdBlocker
  46.         AdBlocker adBlocker = new AdBlocker();
  47.  
  48.         // Test URLs
  49.         string[] urls = {
  50.             "https://www.example.com",
  51.             "https://ads.example.com",
  52.             "https://www.advertisement.com",
  53.             "https://www.example.org"
  54.         };
  55.  
  56.         // Check if each URL is an ad
  57.         foreach (string url in urls)
  58.         {
  59.             bool isAd = adBlocker.IsAd(url);
  60.             Console.WriteLine("{0}: {1}", url, isAd ? "Blocked" : "Allowed");
  61.         }
  62.     }
  63. }
  64.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement