標籤:des style blog class code java
第一步,啟用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 GoogleDriveSamples12 {13 class DriveCommandLineSample14 {15 static void Main(string[] args)16 {17 UserCredential credential = GoogleWebAuthorizationBroker.AuthorizeAsync(18 new ClientSecrets19 {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