How to download a file using Python

To download a file using Python you can use the snippet below.

Sample Python

import urllib.request
import shutil

# file_name = target file name
with urllib.request.urlopen(url) as response, open(file_name, 'wb') as out_file:
    shutil.copyfileobj(response, out_file)

Please rate this snippet

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 send Data using a WebRequest in C# and VB.NET

To send/post Data using a WebRequest in C# and VB.NET you can use the following snippet.

Sample C#

public static string WebrequestWithPost(string url, Encoding dataEncoding, string dataToPost, string contentType = @"application/x-www-form-urlencoded")
{
	var postDataAsByteArray = dataEncoding.GetBytes(dataToPost);
	var returnValue = String.Empty;
	try
	{
		var webRequest = WebRequest.CreateHttp(url);  //change to: var webRequest = (HttpWebRequest)WebRequest.Create(url); if you are your .NET Version is lower than 4.5
		if (webRequest != null)
		{
			webRequest.AllowAutoRedirect = false;
			webRequest.Method = "POST";
			webRequest.ContentType = contentType;
			webRequest.ContentLength = postDataAsByteArray.Length;
			using (var requestDataStream = webRequest.GetRequestStream())
			{
				requestDataStream.Write(postDataAsByteArray, 0, postDataAsByteArray.Length);
				requestDataStream.Close();
				using (var response = webRequest.GetResponse())
				{
					using (var responseDataStream = response.GetResponseStream())
					{
						if (responseDataStream != null)
						{
							using (var responseDataStreamReader = new StreamReader(responseDataStream))
							{
								returnValue = responseDataStreamReader.ReadToEnd();
								responseDataStreamReader.Close();
							}
							responseDataStream.Close();
						}
					}
					response.Close();
				}
				requestDataStream.Close();
			}
		}
	}
	catch (WebException ex)
	{
		if (ex.Status == WebExceptionStatus.ProtocolError)
		{
			var response = ((HttpWebResponse)ex.Response);
			//handle this your own way.
			Console.WriteLine("Webexception! Statuscode: {0}, Description: {1}",(int)response.StatusCode,response.StatusDescription);
		}
	}
	catch(Exception ex) 
	{
		//handle this your own way, something serious happened here.
		Console.WriteLine(ex.Message);
	}
	return returnValue;
}

Sample VB.NET

Public Shared Function WebrequestWithPost(ByVal url As String, ByVal dataEncoding As Encoding, ByVal dataToPost As String, ByVal contentType As String) As String
    Dim postDataAsByteArray As Byte() = dataEncoding.GetBytes(dataToPost)
    Dim returnValue As String = String.Empty
    Try
        Dim webRequest As HttpWebRequest = WebRequest.CreateHttp(url)  'change to: dim webRequest as var = DirectCast(WebRequest.Create(url), HttpWebRequest) if you are your .NET Version is lower than 4.5
        If (Not (webRequest) Is Nothing) Then
            webRequest.AllowAutoRedirect = false
            webRequest.Method = "POST"
            webRequest.ContentType = contentType
            webRequest.ContentLength = postDataAsByteArray.Length
            Dim requestDataStream As Stream = webRequest.GetRequestStream
            requestDataStream.Write(postDataAsByteArray, 0, postDataAsByteArray.Length)
            requestDataStream.Close
            Dim response As Webresponse = webRequest.GetResponse
            Dim responseDataStream As Stream = response.GetResponseStream
            If (Not (responseDataStream) Is Nothing) Then
                Dim responseDataStreamReader As StreamReader = New StreamReader(responseDataStream)
                returnValue = responseDataStreamReader.ReadToEnd
                responseDataStreamReader.Close
                responseDataStream.Close
            End If
            response.Close
            requestDataStream.Close
        End If
    Catch ex As WebException
        If (ex.Status = WebExceptionStatus.ProtocolError) Then
            Dim response As HttpWebResponse = CType(ex.Response,HttpWebResponse)
            'handle this your own way.
            Console.WriteLine("Webexception! Statuscode: {0}, Description: {1}", CType(response.StatusCode,Integer), response.StatusDescription)
        End If
    Catch ex As Exception
        'handle this your own way, something serious happened here.
        Console.WriteLine(ex.Message)
    End Try
    Return returnValue
End Function

FOR MORE INFORMATIONS SEE THE MSDN: How to: Send Data Using the WebRequest Class

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