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

nauna
 
on Mar 05, 2020 06:43 AM
2745 Views

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

Download FREE API for Word, Excel and PDF in ASP.Net: Download
dharmendr
 
on Mar 05, 2020 06:45 AM

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