)>}]
شركة التطبيقات المتكاملة لتصميم وبرمجة البرمجيات الخاصة ش.ش.و.
Integrated Applications Programming Company
Home » Code Library » Drive (Ia.Cl.Models.Google)

Public general use code classes and xml files that we've compiled and used over the years:

Google Drive Directory and File support class.

    1: using global::Google.Apis.Auth.OAuth2;
    2: using global::Google.Apis.Download;
    3: using global::Google.Apis.Drive.v3.Data;
    4: using global::Google.Apis.Services;
    5: using global::Google.Apis.Util.Store;
    6: using Google.Apis.Drive.v3;
    7: using System;
    8: using System.Collections.Generic;
    9: using System.IO;
   10: using System.Linq;
   11: using System.Text;
   12: using System.Threading;
   13:  
   14: namespace Ia.Cl.Models.Google
   15: {
   16:     ////////////////////////////////////////////////////////////////////////////
   17:     /// <summary publish="true">
   18:     /// Google Drive Directory and File support class.
   19:     /// </summary>
   20:     /// <remarks> 
   21:     /// Copyright � 2019-2020 Jasem Y. Al-Shamlan (info@ia.com.kw), Integrated Applications - Kuwait. All Rights Reserved.
   22:     ///
   23:     /// This library is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by
   24:     /// the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
   25:     ///
   26:     /// This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
   27:     /// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
   28:     /// 
   29:     /// You should have received a copy of the GNU General Public License along with this library. If not, see http://www.gnu.org/licenses.
   30:     /// 
   31:     /// Copyright notice: This notice may not be removed or altered from any source distribution.
   32:     /// </remarks> 
   33:  
   34:     public static class Drive
   35:     {
   36:         // If modifying these scopes, delete your previously saved credentials at credentials.json and regenerate them on Google API website.
   37:         // Drag credentials.json(downloaded in Step 1) into your Visual Studio Solution Explorer. Select credentials.json, and then go to the Properties window and set the Copy to Output Directory field to Copy always.
   38:  
   39:         private static readonly string[] scopes = {
   40:             DriveService.Scope.Drive,
   41:             DriveService.Scope.DriveFile,
   42:             DriveService.Scope.DriveAppdata,
   43:             DriveService.Scope.DriveMetadata,
   44:             DriveService.Scope.DriveScripts }; //.DriveReadonly };
   45:  
   46:         private static readonly string applicationName = "Drive API";
   47:  
   48:         ////////////////////////////////////////////////////////////////////////////
   49:  
   50:         /// <summary>
   51:         ///
   52:         /// </summary>
   53:         public static class Directory
   54:         {
   55:             ////////////////////////////////////////////////////////////////////////////
   56:  
   57:             /// <summary>
   58:             ///
   59:             /// </summary>
   60:             public static global::Google.Apis.Drive.v3.Data.File CreateDirectory(string directoryName)
   61:             {
   62:                 global::Google.Apis.Drive.v3.Data.File file, createRequestFile;
   63:                 global::Google.Apis.Drive.v3.FilesResource.CreateRequest createRequest;
   64:  
   65:                 var driveService = CreateDriveService();
   66:  
   67:                 file = new global::Google.Apis.Drive.v3.Data.File
   68:                 {
   69:                     Name = directoryName,
   70:                     Description = string.Empty,
   71:                     MimeType = "application/vnd.google-apps.folder"
   72:                 };
   73:  
   74:                 createRequest = driveService.Files.Create(file);
   75:                 createRequest.Fields = "id";
   76:                 createRequestFile = createRequest.Execute();
   77:  
   78:                 return createRequestFile;
   79:             }
   80:  
   81:             ////////////////////////////////////////////////////////////////////////////
   82:  
   83:             /// <summary>
   84:             ///
   85:             /// </summary>
   86:             public static global::Google.Apis.Drive.v3.Data.File CreateDirectory(string directoryName, string parentDirectoryName)
   87:             {
   88:                 global::Google.Apis.Drive.v3.Data.File file, createRequestFile;
   89:                 global::Google.Apis.Drive.v3.FilesResource.CreateRequest createRequest;
   90:  
   91:                 var list = DriveServiceFileList();
   92:  
   93:                 var parentDirectory = (from f in list where f.Name == parentDirectoryName && f.MimeType == "application/vnd.google-apps.folder" select f).SingleOrDefault();
   94:  
   95:                 var driveService = CreateDriveService();
   96:  
   97:                 file = new global::Google.Apis.Drive.v3.Data.File
   98:                 {
   99:                     Name = directoryName,
  100:                     Description = string.Empty,
  101:                     MimeType = "application/vnd.google-apps.folder",
  102:                     Parents = new List<string> { parentDirectory.Id }
  103:                 };
  104:  
  105:                 createRequest = driveService.Files.Create(file);
  106:                 createRequest.Fields = "id";
  107:                 createRequestFile = createRequest.Execute();
  108:  
  109:                 return createRequestFile;
  110:             }
  111:  
  112:             ////////////////////////////////////////////////////////////////////////////
  113:  
  114:             /// <summary>
  115:             ///
  116:             /// </summary>
  117:             public static List<string> GetFiles()
  118:             {
  119:                 List<string> fileList;
  120:  
  121:                 var list = DriveServiceFileList();
  122:  
  123:                 // get only files
  124:                 fileList = (from f in list where f.MimeType != "application/vnd.google-apps.folder" select f.Name).ToList();
  125:  
  126:                 return fileList;
  127:             }
  128:  
  129:             ////////////////////////////////////////////////////////////////////////////
  130:  
  131:             /// <summary>
  132:             ///
  133:             /// </summary>
  134:             public static List<string> GetDirectories()
  135:             {
  136:                 List<string> directoryList;
  137:  
  138:                 var list = DriveServiceFileList();
  139:  
  140:                 directoryList = (from f in list where f.MimeType == "application/vnd.google-apps.folder" select f.Name).ToList();
  141:  
  142:                 return directoryList;
  143:             }
  144:  
  145:             ////////////////////////////////////////////////////////////////////////////
  146:  
  147:             /// <summary>
  148:             ///
  149:             /// </summary>
  150:             public static bool Exists(string name)
  151:             {
  152:                 bool exists;
  153:                 List<string> directoryList;
  154:  
  155:                 directoryList = GetDirectories();
  156:  
  157:                 exists = directoryList.Count > 0 && directoryList.Contains(name);
  158:  
  159:                 return exists;
  160:             }
  161:  
  162:             ////////////////////////////////////////////////////////////////////////////
  163:  
  164:             /// <summary>
  165:             ///
  166:             /// </summary>
  167:             public static void Delete(string directoryName)
  168:             {
  169:                 var list = DriveServiceFileList();
  170:  
  171:                 var file = (from f in list where f.Name == directoryName && f.MimeType == "application/vnd.google-apps.folder" orderby f.CreatedTime ascending select f).FirstOrDefault();
  172:  
  173:                 var driveService = CreateDriveService();
  174:  
  175:                 try
  176:                 {
  177:                     // Initial validation.    
  178:                     if (driveService == null) throw new ArgumentNullException("driveService");
  179:  
  180:                     if (file == null) throw new ArgumentNullException(file.Id);
  181:  
  182:                     // Make the request.    
  183:                     driveService.Files.Delete(file.Id).Execute();
  184:                 }
  185:                 catch (Exception ex)
  186:                 {
  187:                     throw new Exception("DirectoryDelete() failed: ", ex);
  188:                 }
  189:             }
  190:  
  191:             ////////////////////////////////////////////////////////////////////////////
  192:  
  193:             /// <summary>
  194:             ///
  195:             /// </summary>
  196:             public static bool Move(string sourceDirectoryName, string destinationDirectoryName)
  197:             {
  198:                 string sourceDirectoryFileId, destinationDirectoryFileId;
  199:  
  200:                 var list = DriveServiceFileList();
  201:  
  202:                 sourceDirectoryFileId = (from f in list where f.Name == sourceDirectoryName && f.MimeType == "application/vnd.google-apps.folder" orderby f.CreatedTime ascending select f.Id).FirstOrDefault();
  203:  
  204:                 destinationDirectoryFileId = (from f in list where f.Name == destinationDirectoryName && f.MimeType == "application/vnd.google-apps.folder" orderby f.CreatedTime ascending select f.Id).FirstOrDefault();
  205:  
  206:                 return FileMoveById(sourceDirectoryFileId, destinationDirectoryFileId);
  207:             }
  208:  
  209:             ////////////////////////////////////////////////////////////////////////////
  210:             ////////////////////////////////////////////////////////////////////////////
  211:         }
  212:  
  213:         ////////////////////////////////////////////////////////////////////////////
  214:         ////////////////////////////////////////////////////////////////////////////
  215:  
  216:  
  217:  
  218:  
  219:  
  220:         ////////////////////////////////////////////////////////////////////////////
  221:         ////////////////////////////////////////////////////////////////////////////
  222:  
  223:         ////////////////////////////////////////////////////////////////////////////
  224:  
  225:         /// <summary>
  226:         ///
  227:         /// </summary>
  228:         public static class File
  229:         {
  230:             ////////////////////////////////////////////////////////////////////////////
  231:  
  232:             /// <summary>
  233:             ///
  234:             /// </summary>
  235:             public static global::Google.Apis.Drive.v3.Data.File Create(string fileName)
  236:             {
  237:                 global::Google.Apis.Drive.v3.Data.File file, createRequestFile;
  238:                 global::Google.Apis.Drive.v3.FilesResource.CreateRequest createRequest;
  239:  
  240:                 var driveService = CreateDriveService();
  241:  
  242:                 file = new global::Google.Apis.Drive.v3.Data.File()
  243:                 {
  244:                     Name = fileName,
  245:                     Description = string.Empty,
  246:                     MimeType = MimeTypes.GetMimeType(fileName)
  247:                 };
  248:  
  249:                 createRequest = driveService.Files.Create(file);
  250:                 createRequest.Fields = "id";
  251:                 createRequestFile = createRequest.Execute();
  252:  
  253:                 return createRequestFile;
  254:             }
  255:  
  256:             ////////////////////////////////////////////////////////////////////////////
  257:  
  258:             /// <summary>
  259:             ///
  260:             /// </summary>
  261:             public static bool Exists(string fileName)
  262:             {
  263:                 bool exists;
  264:                 List<string> list;
  265:  
  266:                 list = Directory.GetFiles();
  267:  
  268:                 exists = list.Count > 0 && list.Contains(fileName);
  269:  
  270:                 return exists;
  271:             }
  272:  
  273:             ////////////////////////////////////////////////////////////////////////////
  274:  
  275:             /// <summary>
  276:             ///
  277:             /// </summary>
  278:             public static void Delete(string fileName)
  279:             {
  280:                 var list = DriveServiceFileList();
  281:  
  282:                 var file = (from f in list where f.Name == fileName && f.MimeType != "application/vnd.google-apps.folder" orderby f.CreatedTime ascending select f).FirstOrDefault();
  283:  
  284:                 var driveService = CreateDriveService();
  285:  
  286:                 try
  287:                 {
  288:                     // Initial validation.    
  289:                     if (driveService == null) throw new ArgumentNullException("driveService");
  290:  
  291:                     if (file == null) throw new ArgumentNullException(file.Id);
  292:  
  293:                     // Make the request.    
  294:                     driveService.Files.Delete(file.Id).Execute();
  295:                 }
  296:                 catch (Exception ex)
  297:                 {
  298:                     throw new Exception("FileDelete() failed: ", ex);
  299:                 }
  300:             }
  301:  
  302:             ////////////////////////////////////////////////////////////////////////////
  303:  
  304:             /// <summary>
  305:             ///
  306:             /// </summary>
  307:             public static void WriteAllText(string fileName, string content)
  308:             {
  309:                 string fileId;
  310:                 global::Google.Apis.Drive.v3.Data.File file;
  311:                 global::Google.Apis.Drive.v3.FilesResource.UpdateMediaUpload updateMediaUpload;
  312:                 global::Google.Apis.Drive.v3.FilesResource.CreateMediaUpload createMediaUpload;
  313:  
  314:                 var list = DriveServiceFileList();
  315:  
  316:                 file = (from f in list where f.Name == fileName && f.MimeType != "application/vnd.google-apps.folder" orderby f.CreatedTime ascending select f).FirstOrDefault();
  317:                 fileId = file.Id;
  318:  
  319:                 var driveService = CreateDriveService();
  320:  
  321:                 byte[] byteArray = Encoding.ASCII.GetBytes(content);
  322:  
  323:                 if (file == null)
  324:                 {
  325:                     file = new global::Google.Apis.Drive.v3.Data.File()
  326:                     {
  327:                         Name = fileName,
  328:                         Description = string.Empty,
  329:                         MimeType = MimeTypes.GetMimeType(fileName)
  330:                         // Parents = new List<string> { _parent };
  331:                     };
  332:  
  333:                     using (var memoryStream = new System.IO.MemoryStream(byteArray))
  334:                     {
  335:                         createMediaUpload = driveService.Files.Create(file, memoryStream, file.MimeType);
  336:                         createMediaUpload.Fields = "id";
  337:                         createMediaUpload.Upload();
  338:                     }
  339:                 }
  340:                 else
  341:                 {
  342:                     file = new global::Google.Apis.Drive.v3.Data.File();
  343:  
  344:                     using (var memoryStream = new System.IO.MemoryStream(byteArray))
  345:                     {
  346:                         updateMediaUpload = driveService.Files.Update(file, fileId, memoryStream, file.MimeType);
  347:                         updateMediaUpload.Upload();
  348:                     }
  349:                 }
  350:             }
  351:  
  352:             ////////////////////////////////////////////////////////////////////////////
  353:  
  354:             /// <summary>
  355:             ///
  356:             /// </summary>
  357:             public static string ReadAllText(string fileName)
  358:             {
  359:                 string content;
  360:                 global::Google.Apis.Drive.v3.FilesResource.GetRequest getRequest;
  361:  
  362:                 var list = DriveServiceFileList();
  363:  
  364:                 var file = (from f in list where f.Name == fileName && f.MimeType != "application/vnd.google-apps.folder" orderby f.CreatedTime ascending select f).FirstOrDefault();
  365:  
  366:                 var driveService = CreateDriveService();
  367:  
  368:                 getRequest = driveService.Files.Get(file.Id);
  369:                 getRequest.Execute();
  370:  
  371:                 using (MemoryStream memoryStream = new MemoryStream())
  372:                 {
  373:                     getRequest.Download(memoryStream);
  374:  
  375:                     memoryStream.Position = 0;
  376:  
  377:                     using (System.IO.StreamReader streamReader = new StreamReader(memoryStream, System.Text.Encoding.UTF8, true))
  378:                     {
  379:                         content = streamReader.ReadToEnd();
  380:                     }
  381:                 }
  382:  
  383:                 return content;
  384:             }
  385:  
  386:             ////////////////////////////////////////////////////////////////////////////
  387:  
  388:             /// <summary>
  389:             ///
  390:             /// </summary>
  391:             public static void DownloadFile(string fileName, string downloadPath)
  392:             {
  393:                 string filePath, fileName2;
  394:                 global::Google.Apis.Drive.v3.FilesResource.GetRequest getRequest;
  395:                 MemoryStream memoryStream;
  396:  
  397:                 var list = DriveServiceFileList();
  398:  
  399:                 var file = (from f in list where f.Name == fileName && f.MimeType != "application/vnd.google-apps.folder" orderby f.CreatedTime ascending select f).FirstOrDefault();
  400:  
  401:                 var driveService = CreateDriveService();
  402:  
  403:                 getRequest = driveService.Files.Get(file.Id);
  404:  
  405:                 fileName2 = getRequest.Execute().Name;
  406:                 filePath = System.IO.Path.Combine(downloadPath, fileName2);
  407:  
  408:                 memoryStream = new MemoryStream();
  409:  
  410:                 getRequest.Download(memoryStream);
  411:  
  412:                 SaveStream(memoryStream, filePath);
  413:             }
  414:  
  415:             ////////////////////////////////////////////////////////////////////////////
  416:  
  417:             /// <summary>
  418:             ///
  419:             /// </summary>
  420:             private static void SaveStream(MemoryStream memoryStream, string filePath)
  421:             {
  422:                 using (System.IO.FileStream fileStream = new FileStream(filePath, FileMode.Create, FileAccess.ReadWrite))
  423:                 {
  424:                     memoryStream.WriteTo(fileStream);
  425:                 }
  426:             }
  427:  
  428:             ////////////////////////////////////////////////////////////////////////////
  429:  
  430:             /// <summary>
  431:             ///
  432:             /// </summary>
  433:             public static void UploadFile(string filePath, string directoryName)
  434:             {
  435:                 global::Google.Apis.Drive.v3.FilesResource.CreateMediaUpload createMediaUpload;
  436:  
  437:                 var list = DriveServiceFileList();
  438:  
  439:                 var directory = (from f in list where f.Name == directoryName && f.MimeType == "application/vnd.google-apps.folder" orderby f.CreatedTime ascending select f).FirstOrDefault();
  440:  
  441:                 var driveService = CreateDriveService();
  442:  
  443:                 if (filePath != null)
  444:                 {
  445:                     var file = new global::Google.Apis.Drive.v3.Data.File()
  446:                     {
  447:                         Name = Path.GetFileName(filePath),
  448:                         Description = string.Empty,
  449:                         MimeType = MimeTypes.GetMimeType(filePath),
  450:                         Parents = new List<string> { directory.Id }
  451:                     };
  452:  
  453:                     using (var fileStream = new System.IO.FileStream(filePath, System.IO.FileMode.Open))
  454:                     {
  455:                         createMediaUpload = driveService.Files.Create(file, fileStream, file.MimeType);
  456:                         createMediaUpload.Fields = "id";
  457:                         createMediaUpload.Upload();
  458:                     }
  459:                 }
  460:             }
  461:  
  462:             ////////////////////////////////////////////////////////////////////////////
  463:  
  464:             /// <summary>
  465:             ///
  466:             /// </summary>
  467:             public static bool Move(string sourceFileName, string destinationFileName)
  468:             {
  469:                 string sourceFileId, destinationFileId;
  470:  
  471:                 var list = DriveServiceFileList();
  472:  
  473:                 sourceFileId = (from f in list where f.Name == sourceFileName && f.MimeType != "application/vnd.google-apps.folder" orderby f.CreatedTime ascending select f.Id).FirstOrDefault();
  474:  
  475:                 destinationFileId = (from f in list where f.Name == destinationFileName && f.MimeType != "application/vnd.google-apps.folder" orderby f.CreatedTime ascending select f.Id).FirstOrDefault();
  476:  
  477:                 return FileMoveById(sourceFileId, destinationFileId);
  478:             }
  479:  
  480:             ////////////////////////////////////////////////////////////////////////////
  481:             ////////////////////////////////////////////////////////////////////////////
  482:         }
  483:  
  484:         ////////////////////////////////////////////////////////////////////////////
  485:  
  486:         /// <summary>
  487:         ///
  488:         /// </summary>
  489:         private static bool FileMoveById(string sourceFileId, string destinationFileId)
  490:         {
  491:             // Todo: NotImplementedException()
  492:  
  493:             throw new NotImplementedException();
  494:  
  495:             /*
  496:             bool isSuccessful;
  497:             string previousParents;
  498:             global::Google.Apis.Drive.v3.Data.File file;
  499:             global::Google.Apis.Drive.v3.FilesResource.GetRequest getRequest;
  500:             global::Google.Apis.Drive.v3.FilesResource.UpdateRequest updateRequest;
  501: 
  502:             var driveService = CreateDriveService();
  503: 
  504:             // Retrieve the existing parents to remove    
  505:             getRequest = driveService.Files.Get(sourceFileId);
  506:             getRequest.Fields = "parents";
  507:             file = getRequest.Execute();
  508:             previousParents = string.Join(",", file.Parents);
  509: 
  510:             // Move the file to the new folder    
  511:             updateRequest = driveService.Files.Update(new global::Google.Apis.Drive.v3.Data.File(), sourceFileId);
  512:             updateRequest.Fields = "id, parents";
  513:             updateRequest.AddParents = destinationFileId;
  514:             updateRequest.RemoveParents = previousParents;
  515: 
  516:             file = updateRequest.Execute();
  517: 
  518:             isSuccessful = (file != null);
  519: 
  520:             return isSuccessful;
  521:             */
  522:         }
  523:  
  524:         ////////////////////////////////////////////////////////////////////////////
  525:         ////////////////////////////////////////////////////////////////////////////
  526:  
  527:         /// <summary>
  528:         /// Create Drive API service.
  529:         /// </summary>
  530:         private static global::Google.Apis.Drive.v3.DriveService CreateDriveService()
  531:         {
  532:             string credentialsJsonFilePath, credentialPath;
  533:             UserCredential userCredential;
  534:  
  535:             //credentialsJsonFilePath = @"credentials.json";
  536:             credentialsJsonFilePath = Ia.Cl.Models.Default.AbsolutePath() + "credentials.json";
  537:             //credentialsJsonFilePath = System.Web.Hosting.HostingEnvironment.MapPath(@"~/credentials.json");
  538:  
  539:             //credentialsJsonFilePath = @"C:\Users\Jasem\Documents\Visual Studio 2022\Projects\Integrated Applications\ia.com.kw\credentials.json";
  540:  
  541:             //credentialsJsonFilePath = HttpContext.Current.Server.MapPath(@"~/credentials.json");
  542:  
  543:             using (var fileStream = new FileStream(credentialsJsonFilePath, FileMode.Open, FileAccess.Read))
  544:             {
  545:                 // The file token.json stores the user's access and refresh tokens, and is created automatically when the authorization flow completes for the first time.
  546:                 credentialPath = "token.json";
  547:  
  548:                 userCredential = GoogleWebAuthorizationBroker.AuthorizeAsync(GoogleClientSecrets.Load(fileStream).Secrets, scopes, "user", CancellationToken.None, new FileDataStore(credentialPath, true)).Result;
  549:  
  550:                 //Console.WriteLine("Credential file saved to: " + credPath);
  551:             }
  552:  
  553:             // Create Drive API service.
  554:             var driveService = new DriveService(new BaseClientService.Initializer()
  555:             {
  556:                 HttpClientInitializer = userCredential,
  557:                 ApplicationName = applicationName,
  558:             });
  559:  
  560:             return driveService;
  561:         }
  562:  
  563:         ////////////////////////////////////////////////////////////////////////////
  564:  
  565:         /// <summary>
  566:         ///
  567:         /// </summary>
  568:         private static IList<global::Google.Apis.Drive.v3.Data.File> DriveServiceFileList()
  569:         {
  570:             global::Google.Apis.Drive.v3.FilesResource.ListRequest listRequest;
  571:  
  572:             var driveService = CreateDriveService();
  573:  
  574:             listRequest = driveService.Files.List();
  575:             listRequest.PageSize = 10;
  576:             listRequest.Fields = "nextPageToken, files(*)";
  577:  
  578:             IList<global::Google.Apis.Drive.v3.Data.File> list = listRequest.Execute().Files;
  579:  
  580:             return list;
  581:         }
  582:  
  583:         ////////////////////////////////////////////////////////////////////////////
  584:         ////////////////////////////////////////////////////////////////////////////
  585:     }
  586: }