To get the Youtube VideoId from an Url enerate image thumbnail in C# you can use the following snippet.
Sample Input
/// <summary>
/// Method to reslove the youtube urls into image URL
/// </summary>
/// <param name="youtubeUrl"></param>
/// <returns>imageURL</returns>
public string GetYouTubeThumbnail(string youtubeUrl)
{
string imageURL = string.Empty;
string youTubeThumb = string.Empty;
if (youtubeUrl == "")
return "";
if (youtubeUrl.IndexOf("/embed/") > 0)
{
string strVideoCode = youtubeUrl.Substring(youtubeUrl.IndexOf("/embed/") + 7);
int ind = strVideoCode.IndexOf("?");
youTubeThumb = strVideoCode.Substring(0, ind == -1 ? strVideoCode.Length : ind);
}
else if (youtubeUrl.IndexOf("v=") > 0)
{
string strVideoCode = youtubeUrl.Substring(youtubeUrl.IndexOf("v=") + 2);
int ind = strVideoCode.IndexOf("?");
youTubeThumb = strVideoCode.Substring(0, ind == -1 ? strVideoCode.Length : ind);
}
else if (youtubeUrl.IndexOf("/v/") > 0)
{
string strVideoCode = youtubeUrl.Substring(youtubeUrl.IndexOf("/v/") + 3);
int ind = strVideoCode.IndexOf("?");
youTubeThumb = strVideoCode.Substring(0, ind == -1 ? strVideoCode.Length : ind);
}
else if (youtubeUrl.IndexOf("/") > 6)
{
youTubeThumb = youtubeUrl.Split('/')[1];
}
if (youTubeThumb != string.Empty && youTubeThumb != "" && youTubeThumb != null)
{
imageURL = "http://img.youtube.com/vi/" + youTubeThumb + "/mqdefault.jpg";
}
return imageURL;
}
/// Method to reslove the youtube urls into image URL
/// </summary>
/// <param name="youtubeUrl"></param>
/// <returns>imageURL</returns>
public string GetYouTubeThumbnail(string youtubeUrl)
{
string imageURL = string.Empty;
string youTubeThumb = string.Empty;
if (youtubeUrl == "")
return "";
if (youtubeUrl.IndexOf("/embed/") > 0)
{
string strVideoCode = youtubeUrl.Substring(youtubeUrl.IndexOf("/embed/") + 7);
int ind = strVideoCode.IndexOf("?");
youTubeThumb = strVideoCode.Substring(0, ind == -1 ? strVideoCode.Length : ind);
}
else if (youtubeUrl.IndexOf("v=") > 0)
{
string strVideoCode = youtubeUrl.Substring(youtubeUrl.IndexOf("v=") + 2);
int ind = strVideoCode.IndexOf("?");
youTubeThumb = strVideoCode.Substring(0, ind == -1 ? strVideoCode.Length : ind);
}
else if (youtubeUrl.IndexOf("/v/") > 0)
{
string strVideoCode = youtubeUrl.Substring(youtubeUrl.IndexOf("/v/") + 3);
int ind = strVideoCode.IndexOf("?");
youTubeThumb = strVideoCode.Substring(0, ind == -1 ? strVideoCode.Length : ind);
}
else if (youtubeUrl.IndexOf("/") > 6)
{
youTubeThumb = youtubeUrl.Split('/')[1];
}
if (youTubeThumb != string.Empty && youTubeThumb != "" && youTubeThumb != null)
{
imageURL = "http://img.youtube.com/vi/" + youTubeThumb + "/mqdefault.jpg";
}
return imageURL;
}