首页 > 代码库 > <C#>Google Drive APIs
<C#>Google Drive APIs
第一步,激活Drive API
首先,注册Google帐号;其次,登录Google Developers Console;接着,建立工程和程序;紧接,激活APIs & auth;最后,选择Credentials。
第二步,安装Google Client Library
安装一个NuGet包(Google.Apis.drive)。如在VS2012上,先选择Tools,再NuGet Package Manager,接着Package Manager Console。在PM>中输入Install-Package Google.Apis -Pre,Install-Package Google.Apis.Authentication -Pre,Install-Package Google.Apis.Drive.v2 -Pre。
第三步,编程
1 using System; 2 using System.Threading; 3 using System.Threading.Tasks; 4 5 using Google; 6 using Google.Apis.Auth.OAuth2; 7 using Google.Apis.Drive.v2; 8 using Google.Apis.Drive.v2.Data; 9 using Google.Apis.Services; 10 11 namespace GoogleDriveSamples 12 { 13 class DriveCommandLineSample 14 { 15 static void Main(string[] args) 16 { 17 UserCredential credential = GoogleWebAuthorizationBroker.AuthorizeAsync( 18 new ClientSecrets 19 { 20 ClientId = "CLIENT_ID_HERE", 21 ClientSecret = "CLIENT_SECRET_HERE", 22 }, 23 new[] { DriveService.Scope.Drive }, 24 "user", 25 CancellationToken.None).Result; 26 27 // Create the service. 28 var service = new DriveService(new BaseClientService.Initializer() 29 { 30 HttpClientInitializer = credential, 31 ApplicationName = "Drive API Sample", 32 }); 33 34 File body = new File(); 35 body.Title = "My document"; 36 body.Description = "A test document"; 37 body.MimeType = "text/plain"; 38 39 byte[] byteArray = System.IO.File.ReadAllBytes("document.txt"); 40 System.IO.MemoryStream stream = new System.IO.MemoryStream(byteArray); 41 42 FilesResource.InsertMediaUpload request = service.Files.Insert(body, stream, "text/plain"); 43 request.Upload(); 44 45 File file = request.ResponseBody; 46 Console.WriteLine("File id: " + file.Id); 47 Console.WriteLine("Press Enter to end this process."); 48 Console.ReadLine(); 49 } 50 } 51 }
最后,验证
运行程序后(F5),跳出APIs申请权限,点击“接受”,就运行OK。
摘自:https://developers.google.com/drive/web/quickstart/quickstart-cs
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。