Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove PROTOCOL from URI

Tags:

c#

asp.net

how can I remove the protocol from URI? i.e. remove HTTP

like image 521
Himberjack Avatar asked Dec 23 '10 09:12

Himberjack


5 Answers

You can use this the System.Uri class like this:

System.Uri uri = new Uri("http://stackoverflow.com/search?q=something");
string uriWithoutScheme = uri.Host + uri.PathAndQuery + uri.Fragment;

This will give you stackoverflow.com/search?q=something

Edit: this also works for about:blank :-)

like image 72
Kristof Claes Avatar answered Oct 28 '22 11:10

Kristof Claes


The best (and to me most beautiful) way is to use the Uri class for parsing the string to an absolute URI and then use the GetComponents method with the correct UriComponents enumeration to remove the scheme:

Uri uri;
if (Uri.TryCreate("http://stackoverflow.com/...", UriKind.Absolute, out uri))
{
    return uri.GetComponents(UriComponents.AbsoluteUri &~ UriComponents.Scheme, UriFormat.UriEscaped);
}

For further reference: the UriComponents enumeration is a decorated with the FlagsAttribute, so bitwise operations (eg. & and |) can be used on it. In this case the &~ removes the bits for UriComponents.Scheme from UriComponents.AbsoluteUri using the AND operator in combination with the bitwise complement operator.

like image 18
Ronald Avatar answered Oct 28 '22 10:10

Ronald


In the general sense (not limiting to http/https), an (absolute) uri is always a scheme followed by a colon, followed by scheme-specific data. So the only safe thing to do is cut at the scheme:

    string s = "http://stackoverflow.com/questions/4517240/";
    int i = s.IndexOf(':');
    if (i > 0) s = s.Substring(i + 1);

In the case of http and a few others you may also want to .TrimStart('/'), but this is not part of the scheme, and is not guaranteed to exist. Trivial example: about:blank.

like image 15
Marc Gravell Avatar answered Oct 28 '22 09:10

Marc Gravell


You could use the RegEx for this. The below sample would meet your need.

    using System;
using System.Text.RegularExpressions;

namespace ConsoleApplication1
{
  class Program
  {
    static void Main(string[] args)
    {
      string txt="http://www.google.com";

      string re1="((?:http|https)(?::\\/{2}[\\w]+)(?:[\\/|\\.]?)(?:[^\\s\"]*))";    // HTTP URL 1

      Regex r = new Regex(re1,RegexOptions.IgnoreCase|RegexOptions.Singleline);
      Match m = r.Match(txt);
      if (m.Success)
      {
            String httpurl1=m.Groups[1].ToString();
            Console.Write("("+httpurl1.ToString()+")"+"\n");
      }
      Console.ReadLine();
    }
  }
}

Let me know if this helps

like image 1
clklachu Avatar answered Oct 28 '22 11:10

clklachu


It's not the most beautiful way, but try something like this:

var uri = new Uri("http://www.example.com");
var scheme = uri.Scheme;
var result = uri.ToString().SubString(scheme.Length + 3);
like image 1
fejesjoco Avatar answered Oct 28 '22 10:10

fejesjoco