)>}]
شركة التطبيقات المتكاملة لتصميم وبرمجة البرمجيات الخاصة ش.ش.و.
Integrated Applications Programming Company
Skip Navigation Links

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