Extract Video ID from YouTube URL in C# and VB.Net

Last Reply 29 days ago By dharmendr

Posted 29 days ago

hello,

youtube generate different url in mobile and webbrowser

for website https://www.youtube.com/watch?v=tYbPqiskTZU    

for mobile https://youtu.be/tYbPqiskTZU

i want when user copy and paste any of above link in textbox and click on button want to store only the id of the link i.e  tYbPqiskTZU.

please advice

You are viewing reply posted by: dharmendr 29 days ago.
Posted 29 days ago

Hi nauna,

Refer below code.

C#

string url = "https://youtu.be/tYbPqiskTZU";
//string url = "https://www.youtube.com/watch?v=tYbPqiskTZU";
string id = "";
if (url.Split('/')[url.Split('/').Length - 1].Split('=').Length > 1)
{
    id = url.Split('/')[url.Split('/').Length - 1].Split('=')[1];
}
else
{
    id = url.Split('/')[url.Split('/').Length - 1];
}

VB.Net

Dim url As String = "https://youtu.be/tYbPqiskTZU"
'Dim url As String = "https://www.youtube.com/watch?v=tYbPqiskTZU"
Dim id As String = ""
If url.Split("/"c)(url.Split("/"c).Length - 1).Split("="c).Length > 1 Then
    id = url.Split("/"c)(url.Split("/"c).Length - 1).Split("="c)(1)
Else
    id = url.Split("/"c)(url.Split("/"c).Length - 1)
End If