Aliendreamer

validateurl

Sep 20th, 2018
206
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.89 KB | None | 0 0
  1. using System;
  2. using System.Net;
  3. using System.Text;
  4.  
  5. namespace Task2ValidateURL
  6. {
  7.     class ValidateURL
  8.     {
  9.         static void Main()
  10.         {
  11.             try
  12.             {
  13.                 var inputUri = Console.ReadLine();
  14.                 var uriTest = new Uri(inputUri);
  15.  
  16.                 var result = new StringBuilder();
  17.  
  18.                 if (!uriTest.IsWellFormedOriginalString())
  19.                 {
  20.                     result.AppendLine("Invalid URL");
  21.                 }
  22.  
  23.                 var validHttp = uriTest.Port == 80 && uriTest.Scheme == "http";
  24.                 var validHttps = uriTest.Port == 443 && uriTest.Scheme == "https";
  25.  
  26.                 if (validHttps || validHttp)
  27.                 {
  28.                     result.AppendLine($"Protocol: {uriTest.Scheme}");
  29.                     result.AppendLine($"Host: {uriTest.DnsSafeHost}");
  30.                     result.AppendLine($"Port: {uriTest.Port}");
  31.                     var path = WebUtility.UrlDecode(uriTest.LocalPath);
  32.                     result.AppendLine($"Path: {path}");
  33.  
  34.                     var query = WebUtility.UrlDecode(uriTest.Query);
  35.                     if (uriTest.Query != string.Empty)
  36.                     {
  37.                         result.AppendLine($"Query: {query.TrimStart('?')}");
  38.                     }
  39.  
  40.                     var fragment = WebUtility.UrlDecode(uriTest.Fragment);
  41.                     if (uriTest.Fragment != string.Empty)
  42.                     {
  43.                         result.AppendLine($"Fragment: {fragment.TrimStart('#')}");
  44.                     }
  45.                 }
  46.                 else
  47.                 {
  48.                     result.AppendLine("Invalid URL");
  49.                 }
  50.  
  51.                 Console.WriteLine(result.ToString().Trim());
  52.             }
  53.             catch (Exception e)
  54.             {
  55.                 Console.WriteLine("Invalid URL");
  56.             }
  57.         }
  58.     }
  59. }
Advertisement
Add Comment
Please, Sign In to add comment