How to open a Website in the default Browser in C# and VB.NET

To open a Website in the default Browser in C# and VB.NET you can use the snippet below.

Sample C#

System.Diagnostics.Process.Start("http://codesnippets.fesslersoft.de/");

Sample VB

System.Diagnostics.Process.Start("http://codesnippets.fesslersoft.de/")

Please rate this snippet

How to get the Youtube VideoId from Url in C# and VB.NET

To get the Youtube VideoId from an Url in C# and VB.NET you can use the following snippet.
It matches these 18 type of Youtube Links (Sample Data):

Sample Input

  • http://youtu.be/AAAAAAAAA01
  • http://www.youtube.com/embed/watch?feature=player_embedded&v=AAAAAAAAA02
  • http://www.youtube.com/embed/watch?v=AAAAAAAAA03
  • http://www.youtube.com/embed/v=AAAAAAAAA04
  • http://www.youtube.com/watch?v=AAAAAAAAA06
  • www.youtube.com/watch?v=AAAAAAAAA07
  • www.youtu.be/AAAAAAAAA08
  • youtu.be/AAAAAAAAA09
  • http://www.youtube.com/watch?feature=player_embedded&v=AAAAAAAAA05
  • http://www.youtube.com/watch?v=i-AAAAAAA14&feature=related
  • http://www.youtube.com/attribution_link?u=/watch?v=AAAAAAAAA15&feature=share&a=9QlmP1yvjcllp0h3l0NwuA
  • http://www.youtube.com/attribution_link?a=fF1CWYwxCQ4&u=/watch?v=AAAAAAAAA16&feature=em-uploademail
  • http://www.youtube.com/attribution_link?a=fF1CWYwxCQ4&feature=em-uploademail&u=/watch?v=AAAAAAAAA17
  • http://www.youtube.com/v/A-AAAAAAA18?fs=1&rel=0
  • youtube.com/watch?v=AAAAAAAAA10
  • http://www.youtube.com/watch/AAAAAAAAA11
  • http://www.youtube.com/v/AAAAAAAAA12
  • http://www.youtube.com/v/AAAAAAAAA13
  • Sample C#

    using System.Linq;
    using System.Text.RegularExpressions;
    
    namespace de.fesslersoft.YoutubeRegexTest
    {
        internal static class Youtube
        {
            private const string YoutubeLinkRegex = "(?:.+?)?(?:\\/v\\/|watch\\/|\\?v=|\\&v=|youtu\\.be\\/|\\/v=|^youtu\\.be\\/)([a-zA-Z0-9_-]{11})+";
    
            internal static string GetVideoId(string input)
            {
                var regex = new Regex(YoutubeLinkRegex, RegexOptions.Compiled);
                foreach (Match match in regex.Matches(input))
                {
                    //Console.WriteLine(match);
                    foreach (var groupdata in match.Groups.Cast<Group>().Where(groupdata => !groupdata.ToString().StartsWith("http://") && !groupdata.ToString().StartsWith("https://") && !groupdata.ToString().StartsWith("youtu") && !groupdata.ToString().StartsWith("www.")))
                    {
                        return groupdata.ToString();
                    }
                }
                return string.Empty;
            }
        }
    }
    

    Sample VB.NET

    Imports System.Linq
    Imports System.Text.RegularExpressions
     
    Namespace de.fesslersoft.YoutubeRegexTest
        Friend NotInheritable Class Youtube
            Private Sub New()
            End Sub
            Private Const YoutubeLinkRegex As String = "(?:.+?)?(?:\/v\/|watch\/|\?v=|\&v=|youtu\.be\/|\/v=|^youtu\.be\/)([a-zA-Z0-9_-]{11})+"
     
            Friend Shared Function GetVideoId(input As String) As String
                Dim regex = New Regex(YoutubeLinkRegex, RegexOptions.Compiled)
                For Each match As Match In regex.Matches(input)
                    For Each data As Group In match.Groups.Cast(Of Group)().Where(Function(groupdata) Not groupdata.ToString().StartsWith("http://") AndAlso Not groupdata.ToString().StartsWith("https://") AndAlso Not groupdata.ToString().StartsWith("youtu") AndAlso Not groupdata.ToString().StartsWith("www."))
                        Return data.ToString()
                    Next
                Next
                Return String.Empty
            End Function
        End Class
    End Namespace
    

    Output / Sample

    var urlList = new List<String>
    {
    	"http://youtu.be/AAAAAAAAA01",
    	"http://www.youtube.com/embed/watch?feature=player_embedded&v=AAAAAAAAA02",
    	"http://www.youtube.com/embed/watch?v=AAAAAAAAA03",
    	"http://www.youtube.com/embed/v=AAAAAAAAA04",
    	"http://www.youtube.com/watch?feature=player_embedded&v=AAAAAAAAA05",
    	"http://www.youtube.com/watch?v=AAAAAAAAA06",
    	"www.youtube.com/watch?v=AAAAAAAAA07",
    	"www.youtu.be/AAAAAAAAA08",
    	"youtu.be/AAAAAAAAA09",
    	"youtube.com/watch?v=AAAAAAAAA10",
    	"http://www.youtube.com/watch/AAAAAAAAA11",
    	"http://www.youtube.com/v/AAAAAAAAA12",
    	"http://www.youtube.com/v/AAAAAAAAA13",
    	"http://www.youtube.com/watch?v=i-AAAAAAA14&feature=related",
    	"http://www.youtube.com/attribution_link?u=/watch?v=AAAAAAAAA15&feature=share&a=9QlmP1yvjcllp0h3l0NwuA",
    	"http://www.youtube.com/attribution_link?a=fF1CWYwxCQ4&u=/watch?v=AAAAAAAAA16&feature=em-uploademail",
    	"http://www.youtube.com/attribution_link?a=fF1CWYwxCQ4&feature=em-uploademail&u=/watch?v=AAAAAAAAA17",
    	"http://www.youtube.com/v/A-AAAAAAA18?fs=1&rel=0"
    };
    
    foreach (var entry in urlList)
    {
    	Console.WriteLine(Youtube.GetVideoId(entry));
    }
    Console.Read();
    

    will result in the follwing output:

    Youtube VideoId Regex Console Window Output

    Youtube VideoId Regex Console Window Output

    A simpler but less matching solution can be found here: How to get the VideoID of a youtube video using Regex

    Please rate this snippet

    How to combine multiple Uri in C# and VB.NET

    To combine multiple Uri in C# and VB.NET you can use the following snippet.

    Simple Sample (combining 2 uri)

    Sample C#

    public string CombineUri(string uri1, string uri2)
    {
    	if (uri1.Length == 0){return uri2;}
    	if (uri2.Length == 0){return uri1;}
    	uri1 = uri1.TrimEnd('/', '\\');
    	uri2 = uri2.TrimStart('/', '\\');
    	return string.Format("{0}/{1}", uri1, uri2);
    }
    

    Sample VB.NET (autogenerated)

    Public Function CombineUri(uri1 As String, uri2 As String) As String
    	If uri1.Length = 0 Then
    		Return uri2
    	End If
    	If uri2.Length = 0 Then
    		Return uri1
    	End If
    	uri1 = uri1.TrimEnd("/", "\")
    	uri2 = uri2.TrimStart("/", "\")
    	Return String.Format("{0}/{1}", uri1, uri2)
    End Function
    

    UPDATE 23.06.2015

    Combine multiple Uri

    Since this snippet is one of our most read snippets of all time, i decided to upgrade this snippet.
    This method now uses params string[] as method parameter which allows much more uri strings to be combine at once.

    Sample C#

    public string CombineUri(params string[] uriParams)
    {
    	var retVal = string.Empty;
    	foreach (var uriParam in uriParams)
    	{
    		var tempParam = uriParam.Trim();
    		if (!String.IsNullOrEmpty(tempParam))
    		{
    			tempParam = uriParam.TrimEnd('/', '\\');
    			retVal = !String.IsNullOrEmpty(retVal) ? string.Format("{0}/{1}", retVal, tempParam) : string.Format("{0}", tempParam);
    		}
    	}
    	return retVal;
    }
    

    Sample VB.NET (autogenerated)

    Public Function CombineUri(ParamArray uriParams As String()) As String
    	Dim retVal = String.Empty
    	For Each uriParam As var In uriParams
    		Dim tempParam = uriParam.Trim()
    		If Not [String].IsNullOrEmpty(tempParam) Then
    			tempParam = uriParam.TrimEnd("/"C, "\"C)
    			retVal = If(Not [String].IsNullOrEmpty(retVal), String.Format("{0}/{1}", retVal, tempParam), String.Format("{0}", tempParam))
    		End If
    	Next
    	Return retVal
    End Function
    

    For more informations about params see the msdn: params (C# Reference)

    Please rate this snippet

    How to ping in Java

    To ping in Java you can use the following snippet.

    Sample Java

    public static void pingUrl(String url, Integer timeOut)
    {
    	url = url.replace("http://", "");
    	try {  
    		InetAddress address = InetAddress.getByName(url);  
    		System.out.println("Hostname: " + address.getHostName());  
    		System.out.println("IP-Address: " + address.getHostAddress());  
    		System.out.println("Reachable in " + ((double)timeOut / (double)1000) + " Seconds: " + address.isReachable(timeOut));  
    	}  
    	catch (UnknownHostException e) {
    		System.err.println("Unable to lookup " + url + "; error: " + e);  
    	}  
    	catch (IOException e) {  
    		System.err.println("Unable to reach " + url);  
    	}  
    }
    

    Please rate this snippet

    How to download a website source in Java

    To download a website source in Java you can use the following snippet.

    Sample Java

    private static String getUrlSource(String url) throws IOException {
    	URL website = new URL(url);
    	URLConnection connection = website.openConnection();
    	BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
    	String input;
    	StringBuilder strBuilder = new StringBuilder();
    	while ((input = bufferedReader.readLine()) != null){
    			strBuilder.append(input);
    	}
    	bufferedReader.close();
    	return strBuilder.toString();
    }
    

    Please rate this snippet

    How to download a image from url in C# and VB.NET

    Sample C#

    private static void DownloadImage(string url, string saveFilename)
    {
    	var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
    	var httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
    	if ((httpWebResponse.StatusCode != HttpStatusCode.OK && 
    		httpWebResponse.StatusCode != HttpStatusCode.Moved && 
    		httpWebResponse.StatusCode != HttpStatusCode.Redirect) 
    		|| !httpWebResponse.ContentType.StartsWith("image", StringComparison.OrdinalIgnoreCase))
    	{
    		return;
    	}
    	using (var stream = httpWebResponse.GetResponseStream())
    	using (var fileStream = File.OpenWrite(saveFilename))
    	{
    		var bytes = new byte[4096];
    		var read=0;
    		do
    		{
    			if (stream == null) {continue;}
    			read = stream.Read(bytes, 0, bytes.Length);
    			fileStream.Write(bytes, 0, read);
    		} while (read != 0);
    	}
    }
    

    Sample VB.NET

    Private Shared Sub DownloadImage(url As String, saveFilename As String)
    	Dim httpWebRequest = DirectCast(WebRequest.Create(url), HttpWebRequest)
    	Dim httpWebResponse = DirectCast(httpWebRequest.GetResponse(), HttpWebResponse)
    	If (httpWebResponse.StatusCode <> HttpStatusCode.OK AndAlso httpWebResponse.StatusCode <> HttpStatusCode.Moved AndAlso httpWebResponse.StatusCode <> HttpStatusCode.Redirect) OrElse Not httpWebResponse.ContentType.StartsWith("image", StringComparison.OrdinalIgnoreCase) Then
    		Return
    	End If
    	Using stream = httpWebResponse.GetResponseStream()
    		Using fileStream = File.OpenWrite(saveFilename)
    			Dim bytes = New Byte(4095) {}
    			Dim read = 0
    			Do
    				If stream Is Nothing Then
    					Continue Do
    				End If
    				read = stream.Read(bytes, 0, bytes.Length)
    				fileStream.Write(bytes, 0, read)
    			Loop While read <> 0
    		End Using
    	End Using
    End Sub
    

    Please rate this snippet

    How to get the source of a website in C# and VB.NET

    To get the source of a website in C# and VB.NET you can use the following snippet.

    Sample C#

    public static string GetHtmlSourceFromUri(string uri)
    {
    	var retVal = string.Empty;
    	var request = (HttpWebRequest)System.Net.WebRequest.Create(uri);
    	using (var response = (HttpWebResponse)request.GetResponse())
    	{
    		bool success = (int)response.StatusCode >= 200 && (int)response.StatusCode < 299;
    		if (success)
    		{
    			var responseStream = response.GetResponseStream();
    			if (responseStream != null)
    			{
    				using (var reader = new StreamReader(responseStream,Encoding.UTF8))
    				{
    					retVal = reader.ReadToEnd();
    				}
    			}
    		}
    	}
    	return retVal;
    }
    

    Sample Vb.NET

    Public Shared Function GetHtmlSourceFromUri(uri As String) As String
    	Dim retVal = String.Empty
    	Dim request = DirectCast(System.Net.WebRequest.Create(uri), HttpWebRequest)
    	Using response = DirectCast(request.GetResponse(), HttpWebResponse)
    		Dim success As Boolean = CInt(response.StatusCode) >= 200 AndAlso CInt(response.StatusCode) < 299
    		If success Then
    			Dim responseStream = response.GetResponseStream()
    			If responseStream IsNot Nothing Then
    				Using reader = New StreamReader(responseStream,Encoding.UTF8)
    					retVal = reader.ReadToEnd()
    				End Using
    			End If
    		End If
    	End Using
    	Return retVal
    End Function
    

    Please rate this snippet

    How to get the filename of url in C# and VB.NET

    To get the filename of a url in C# and VB.NET you can use the following snippet.

    Sample C#

    public static string GetFilenameFromUrl(string url)
    {
    	return String.IsNullOrEmpty(url.Trim()) || !url.Contains(".") ? string.Empty : Path.GetFileName(new Uri(url).AbsolutePath);
    }
    

    Sample VB.NET

    Public Shared Function GetFilenameFromUrl(url As String) As String
    	Return If([String].IsNullOrEmpty(url.Trim()) OrElse Not url.Contains("."), String.Empty, Path.GetFileName(New Uri(url).AbsolutePath))
    End Function
    

    Please rate this snippet