using Google.Apis.Auth.OAuth2; using Google.Apis.Drive.v2; using Google.Apis.Drive.v2.Data; using Google.Apis.Services; using Google.Apis.Util.Store; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace SyncDump { class Program { /// <summary> /// 存取權限 /// </summary> static string[] Scopes = { DriveService.Scope.Drive, DriveService.Scope.DriveFile }; static string ApplicationName = "Drive Uploader"; static void Main(string[] args) { // 檢查輸入參數 if (args.Length < 1) { Console.WriteLine("No target file argument!"); return; } // 要上傳的檔案 string dumpPath = args[0]; string dumpName = System.IO.Path.GetFileName(dumpPath); // 載入驗證資訊 GoogleCredential credential; using (var stream = new System.IO.FileStream("client_secret.json", System.IO.FileMode.Open, System.IO.FileAccess.Read)) { credential = GoogleCredential.FromStream(stream); } // 建立 service DriveService service = new DriveService(new BaseClientService.Initializer() { HttpClientInitializer = credential.CreateScoped(Scopes), ApplicationName = ApplicationName }); // 進行上傳 insertFile( service, dumpName, dumpName, System.Configuration.ConfigurationManager.AppSettings["drive.folder.id"], "application/oct-stream", dumpPath ); } /// <summary> /// 新增檔案 /// </summary> /// <param name="service">Drive API service instance.</param> /// <param name="title">Title of the file to insert, including the extension.</param> /// <param name="description">Description of the file to insert.</param> /// <param name="parentId">Parent folder's ID.</param> /// <param name="mimeType">MIME type of the file to insert.</param> /// <param name="filename">Filename of the file to insert.</param><br> /// <returns>Inserted file metadata, null is returned if an API error occurred.</returns> private static File insertFile(DriveService service, string title, string description, string parentId, string mimeType, string filename) { // 檔案資訊 File body = new File(); body.Title = title; body.Description = description; body.MimeType = mimeType; // 設定上傳位置 if (!string.IsNullOrEmpty(parentId)) { body.Parents = new List<ParentReference>() { new ParentReference() { Id = parentId } }; } // 檔案內容 byte[] byteArray = System.IO.File.ReadAllBytes(filename); System.IO.MemoryStream stream = new System.IO.MemoryStream(byteArray); try { FilesResource.InsertMediaUpload request = service.Files.Insert(body, stream, mimeType); request.Upload(); File file = request.ResponseBody; Console.WriteLine("{0:yyyy/MM/dd HH:mm:ss} File {1} is uploaded to drive", DateTime.Now, file.Title); return file; } catch (Exception e) { Console.WriteLine("An error occurred: " + e.Message); return null; } } } }