fork download
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading;
  6. using System.Threading.Tasks;
  7. using Google.Apis.Auth.OAuth2;
  8. using Google.Apis.Download;
  9. using Google.Apis.Drive.v2;
  10. using Google.Apis.Drive.v2.Data;
  11. using Google.Apis.Services;
  12. using Google.Apis.Upload;
  13.  
  14.  
  15. namespace GoogleDriveTest
  16. {
  17. /// <summary>
  18. /// A sample for the Drive API. This samples demonstrates resumable media upload and media download.
  19. /// See https://developers.google.com/drive/ for more details regarding the Drive API.
  20. /// </summary>
  21. class Program
  22. {
  23. static Program()
  24. {
  25. // initialize the log instance
  26. //ApplicationContext.RegisterLogger(new Log4NetLogger());
  27. }
  28.  
  29. #region Consts
  30.  
  31. private const int KB = 0x400;
  32. private const int DownloadChunkSize = 256 * KB;
  33.  
  34. // CHANGE THIS with full path to the file you want to upload
  35. private const string UploadFileName = @"C:\Users\eren.CORP\Desktop\GoogleDriveTestFolder\1.jpg";
  36.  
  37. // CHANGE THIS with a download directory
  38. private const string DownloadDirectoryName = @"C:\Users\eren.CORP\Desktop\GoogleDriveTestFolder";
  39.  
  40. // CHANGE THIS if you upload a file type other than a jpg
  41. private const string ContentType = @"image/jpeg";
  42.  
  43. #endregion
  44.  
  45. /// <summary>The Drive API scopes.</summary>
  46. private static readonly string[] Scopes = new[] { DriveService.Scope.DriveFile, DriveService.Scope.Drive };
  47.  
  48. /// <summary>
  49. /// The file which was uploaded. We will use its download Url to download it using our media downloader object.
  50. /// </summary>
  51. private static File uploadedFile;
  52.  
  53. static void Main(string[] args)
  54. {
  55. Console.WriteLine("Google Drive API Sample");
  56.  
  57. try
  58. {
  59. new Program().Run().Wait();
  60. }
  61. catch (AggregateException ex)
  62. {
  63. foreach (var e in ex.InnerExceptions)
  64. {
  65. Console.WriteLine("ERROR: " + e.Message);
  66. }
  67. }
  68.  
  69. Console.WriteLine("Press any key to continue...");
  70. Console.ReadKey();
  71. }
  72.  
  73. private async Task Run()
  74. {
  75. GoogleWebAuthorizationBroker.Folder = "Drive.Sample";
  76. UserCredential credential;
  77. using (var stream = new System.IO.FileStream("client_secrets.json",
  78. System.IO.FileMode.Open, System.IO.FileAccess.Read))
  79. {
  80. credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
  81. GoogleClientSecrets.Load(stream).Secrets, Scopes, "user", CancellationToken.None);
  82. }
  83.  
  84. // Create the service.
  85. var service = new DriveService(new BaseClientService.Initializer()
  86. {
  87. HttpClientInitializer = credential,
  88. ApplicationName = "Drive API Sample",
  89. });
  90.  
  91. await UploadFileAsync(service);
  92.  
  93. // uploaded succeeded
  94. Console.WriteLine("\"{0}\" was uploaded successfully", uploadedFile.Title);
  95. var fileId = uploadedFile.Id;
  96. await DownloadFile(service, uploadedFile.DownloadUrl);
  97. await DeleteFile(service, uploadedFile);
  98.  
  99. }
  100.  
  101. /// <summary>Uploads file asynchronously.</summary>
  102. private Task<IUploadProgress> UploadFileAsync(DriveService service)
  103. {
  104. var title = UploadFileName;
  105. if (title.LastIndexOf('\\') != -1)
  106. {
  107. title = title.Substring(title.LastIndexOf('\\') + 1);
  108. }
  109.  
  110. var uploadStream = new System.IO.FileStream(UploadFileName, System.IO.FileMode.Open,
  111. System.IO.FileAccess.Read);
  112.  
  113. var insert = service.Files.Insert(new File { Title = title }, uploadStream, ContentType);
  114.  
  115. insert.ChunkSize = FilesResource.InsertMediaUpload.MinimumChunkSize * 2;
  116. insert.ProgressChanged += Upload_ProgressChanged;
  117. insert.ResponseReceived += Upload_ResponseReceived;
  118.  
  119. var task = insert.UploadAsync();
  120.  
  121. task.ContinueWith(t =>
  122. {
  123. // NotOnRanToCompletion - this code will be called if the upload fails
  124. Console.WriteLine("Upload Filed. " + t.Exception);
  125. }, TaskContinuationOptions.NotOnRanToCompletion);
  126. task.ContinueWith(t =>
  127. {
  128. // Logger.Debug("Closing the stream");
  129. uploadStream.Dispose();
  130. // Logger.Debug("The stream was closed");
  131. });
  132.  
  133. return task;
  134. }
  135.  
  136. /// <summary>Downloads the media from the given URL.</summary>
  137. private async Task DownloadFile(DriveService service, string url)
  138. {
  139. var downloader = new MediaDownloader(service);
  140. downloader.ChunkSize = DownloadChunkSize;
  141. // add a delegate for the progress changed event for writing to console on changes
  142. downloader.ProgressChanged += Download_ProgressChanged;
  143.  
  144. // figure out the right file type base on UploadFileName extension
  145. var lastDot = UploadFileName.LastIndexOf('.');
  146. var fileName = DownloadDirectoryName + @"\Download" +
  147. (lastDot != -1 ? "." + UploadFileName.Substring(lastDot + 1) : "");
  148. using (var fileStream = new System.IO.FileStream(fileName,
  149. System.IO.FileMode.Create, System.IO.FileAccess.Write))
  150. {
  151. var progress = await downloader.DownloadAsync(url, fileStream);
  152. if (progress.Status == DownloadStatus.Completed)
  153. {
  154. Console.WriteLine(fileName + " was downloaded successfully");
  155. }
  156. else
  157. {
  158. Console.WriteLine("Download {0} was interpreted in the middle. Only {1} were downloaded. ",
  159. fileName, progress.BytesDownloaded);
  160. }
  161. }
  162. }
  163.  
  164. /// <summary>Deletes the given file from drive (not the file system).</summary>
  165. private async Task DeleteFile(DriveService service, File file)
  166. {
  167. Console.WriteLine("Deleting file '{0}'...", file.Id);
  168. await service.Files.Delete(file.Id).ExecuteAsStreamAsync();
  169. Console.WriteLine("File was deleted successfully");
  170. }
  171.  
  172. #region Progress and Response changes
  173.  
  174. static void Download_ProgressChanged(IDownloadProgress progress)
  175. {
  176. Console.WriteLine(progress.Status + " " + progress.BytesDownloaded);
  177. }
  178.  
  179. static void Upload_ProgressChanged(IUploadProgress progress)
  180. {
  181. Console.WriteLine(progress.Status + " " + progress.BytesSent);
  182. }
  183.  
  184. static void Upload_ResponseReceived(File file)
  185. {
  186. uploadedFile = file;
  187. }
  188.  
  189. #endregion
  190. }
  191. }
  192.  
Compilation error #stdin compilation error #stdout 0s 0KB
stdin
Standard input is empty
compilation info
prog.cs(73,30): error CS1519: Unexpected symbol `Run' in class, struct, or interface member declaration
prog.cs(73,28): error CS1520: Class, struct, or interface method must have a return type
prog.cs(80,35): error CS1525: Unexpected symbol `GoogleWebAuthorizationBroker'
prog.cs(91,33): error CS1525: Unexpected symbol `(', expecting `,', `;', or `='
prog.cs(96,30): error CS1525: Unexpected symbol `(', expecting `,', `;', or `='
prog.cs(96,52): error CS1525: Unexpected symbol `.', expecting `,', `;', or `='
prog.cs(97,28): error CS1525: Unexpected symbol `(', expecting `,', `;', or `='
prog.cs(97,50): error CS1525: Unexpected symbol `)', expecting `,', `;', or `='
prog.cs(137,39): error CS1519: Unexpected symbol `DownloadFile' in class, struct, or interface member declaration
prog.cs(137,28): error CS1520: Class, struct, or interface method must have a return type
prog.cs(151,37): error CS1525: Unexpected symbol `downloader'
prog.cs(151,68): error CS0136: A local variable named `fileStream' cannot be declared in this scope because it would give a different meaning to `fileStream', which is already used in a `parent or current' scope to denote something else
prog.cs(151,77): error CS1525: Unexpected symbol `)'
prog.cs(165,37): error CS1519: Unexpected symbol `DeleteFile' in class, struct, or interface member declaration
prog.cs(165,28): error CS1520: Class, struct, or interface method must have a return type
prog.cs(168,19): error CS0128: A local variable named `service' is already defined in this scope
prog.cs(168,25): error CS1525: Unexpected symbol `.', expecting `,', `;', or `='
Compilation failed: 17 error(s), 0 warnings
stdout
Standard output is empty