· 6 years ago · Jan 29, 2020, 09:02 PM
1using System;
2using System.Collections.Generic;
3using System.IO;
4using System.Reflection;
5using System.Threading;
6using System.Threading.Tasks;
7
8using Google.Apis.Auth.OAuth2;
9using Google.Apis.Services;
10using Google.Apis.Upload;
11using Google.Apis.Util.Store;
12using Google.Apis.YouTube.v3;
13using Google.Apis.YouTube.v3.Data;
14
15namespace testAPI {
16 /// <summary>
17 /// YouTube Data API v3 sample: search by keyword.
18 /// Relies on the Google APIs Client Library for .NET, v1.7.0 or higher.
19 /// See https://developers.google.com/api-client-library/dotnet/get_started
20 ///
21 /// Set ApiKey to the API key value from the APIs & auth > Registered apps tab of
22 /// https://cloud.google.com/console
23 /// Please ensure that you have enabled the YouTube Data API for your project.
24 /// </summary>
25 internal class Search {
26 [STAThread]
27 static void Main(string[] args) {
28 Console.WriteLine("YouTube Data API: Search");
29 Console.WriteLine("========================");
30
31 try {
32 new Search().Run().Wait();
33 }
34 catch (AggregateException ex) {
35 foreach (var e in ex.InnerExceptions) {
36 Console.WriteLine("Error: " + e.Message);
37 }
38 }
39
40 Console.WriteLine("Press any key to continue...");
41 Console.ReadKey();
42 }
43
44 private async Task Run() {
45 var youtubeService = new YouTubeService(new BaseClientService.Initializer() {
46 ApiKey = "AIzaSyBOStztGblK6AgSRP_F1ujkgoOK1ZE-dAA",
47 ApplicationName = this.GetType().ToString()
48 });
49
50 var searchListRequest = youtubeService.Search.List("snippet");
51 searchListRequest.Q = "Mandarynka"; // Replace with your search term.
52 searchListRequest.MaxResults = 6;
53
54 // Call the search.list method to retrieve results matching the specified query term.
55 var searchListResponse = await searchListRequest.ExecuteAsync();
56
57 List<string> videos = new List<string>();
58 List<string> channels = new List<string>();
59 List<string> playlists = new List<string>();
60
61 // Add each result to the appropriate list, and then display the lists of
62 // matching videos, channels, and playlists.
63 foreach (var searchResult in searchListResponse.Items) {
64 switch (searchResult.Id.Kind) {
65 case "youtube#video":
66 videos.Add(String.Format("{0} ({1})", searchResult.Snippet.Title, searchResult.Id.VideoId));
67 break;
68
69 case "youtube#channel":
70 channels.Add(String.Format("{0} ({1})", searchResult.Snippet.Title, searchResult.Id.ChannelId));
71 break;
72
73 case "youtube#playlist":
74 playlists.Add(String.Format("{0} ({1})", searchResult.Snippet.Title, searchResult.Id.PlaylistId));
75 break;
76 }
77 }
78
79 Console.WriteLine(String.Format("Videos:\n{0}\n", string.Join("\n", videos)));
80 }
81 }
82}