Example #1
0
        //public static void FileUploadInFolder(string folderId, HttpPostedFileBase file)
        //{
        //    if (file != null && file.ContentLength > 0)
        //    {
        //        Google.Apis.Drive.v3.DriveService service = GetService_v3();

        //        string path = Path.Combine(HttpContext.Current.Server.MapPath("~/GoogleDriveFiles"),
        //        Path.GetFileName(file.FileName));
        //        file.SaveAs(path);

        //        var FileMetaData = new Google.Apis.Drive.v3.Data.File()
        //        {
        //            Name = Path.GetFileName(file.FileName),
        //            MimeType = MimeMapping.GetMimeMapping(path),
        //            Parents = new List<string>
        //            {
        //                folderId
        //            }
        //        };

        //        Google.Apis.Drive.v3.FilesResource.CreateMediaUpload request;
        //        using (var stream = new System.IO.FileStream(path, System.IO.FileMode.Open))
        //        {
        //            request = service.Files.Create(FileMetaData, stream, FileMetaData.MimeType);
        //            request.Fields = "id";
        //            request.Upload();
        //        }
        //        var file1 = request.ResponseBody;
        //    }
        //}
        public static List <GoogleDriveFiles> GetDriveFiles()
        {
            Google.Apis.Drive.v3.DriveService service = GetService_v3();

            // Define parameters of request.
            Google.Apis.Drive.v3.FilesResource.ListRequest FileListRequest = service.Files.List();
            FileListRequest.Fields = "nextPageToken, files(createdTime, id, name, size, version, trashed, parents)";

            // List files.
            IList <Google.Apis.Drive.v3.Data.File> files = FileListRequest.Execute().Files;
            List <GoogleDriveFiles> FileList             = new List <GoogleDriveFiles>();

            if (files != null && files.Count > 0)
            {
                foreach (var file in files)
                {
                    GoogleDriveFiles File = new GoogleDriveFiles
                    {
                        Id          = file.Id,
                        Name        = file.Name,
                        Size        = file.Size,
                        Version     = file.Version,
                        CreatedTime = file.CreatedTime,
                        Parents     = file.Parents
                    };
                    FileList.Add(File);
                }
            }
            return(FileList);
        }
Example #2
0
        public static void FileUploadInFolder(string folderId, HttpPostedFileBase[] files, ref string videoID)
        {
            foreach (HttpPostedFileBase file in files)
            {
                if (file != null && file.ContentLength > 0)
                {
                    Google.Apis.Drive.v3.DriveService service = GetService_v3();

                    string path = Path.Combine(HttpContext.Current.Server.MapPath("~/Areas/GoogleDriveFiles"),
                                               Path.GetFileName(file.FileName));
                    file.SaveAs(path);

                    var FileMetaData = new Google.Apis.Drive.v3.Data.File()
                    {
                        Name     = Path.GetFileName(file.FileName),
                        MimeType = MimeMapping.GetMimeMapping(path),
                        Parents  = new List <string>
                        {
                            folderId
                        }
                    };

                    Google.Apis.Drive.v3.FilesResource.CreateMediaUpload request;
                    using (var stream = new System.IO.FileStream(path, System.IO.FileMode.Open))
                    {
                        request                    = service.Files.Create(FileMetaData, stream, FileMetaData.MimeType);
                        request.Fields             = "id";
                        request.SupportsTeamDrives = true;
                        request.Upload();
                    }
                    var file1 = request.ResponseBody;
                    videoID = file1.Id;
                }
            }
        }
Example #3
0
        /// <summary>
        /// Lista todos os arquivos do diretorio
        /// </summary>
        /// <param name="servico"></param>
        public List <claNegocioBackup> ListarArquivos(Google.Apis.Drive.v3.DriveService servico)
        {
            msgErro = "";

            var request = servico.Files.List();

            request.Spaces = "drive";
            request.Fields = "files(id, name)";
            request.Q      = "mimeType='application/zip' and trashed=false";

            var resultado = request.Execute();
            var arquivos  = resultado.Files;

            List <claNegocioBackup> lstArquivos = new List <claNegocioBackup>();

            if (arquivos != null && arquivos.Any())
            {
                foreach (var arquivo in arquivos)
                {
                    claNegocioBackup objBackup = new claNegocioBackup();
                    objBackup.fdNomeItem = arquivo.Name.ToString();
                    lstArquivos.Add(objBackup);
                }
            }
            return(lstArquivos);
        }
Example #4
0
        public static Google.Apis.Drive.v3.DriveService GetService_v3()
        {
            UserCredential credential;

            using (var stream = new FileStream(@"D:\GitRepo\OnlineMovie-master\credentials.json", FileMode.Open, FileAccess.Read))
            {
                String FolderPath = @"D:\GitRepo\OnlineMovie-master\";
                String FilePath   = Path.Combine(FolderPath, "DriveServiceCredentials.json");

                credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                    GoogleClientSecrets.Load(stream).Secrets,
                    Scopes,
                    "user",
                    CancellationToken.None,
                    new FileDataStore(FilePath, true)).Result;
            }

            //Create Drive API service.
            Google.Apis.Drive.v3.DriveService service = new Google.Apis.Drive.v3.DriveService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName       = "GoogleDriveRestAPI-v3",
            });

            return(service);
        }
Example #5
0
        private void frmInicio_Load(object sender, EventArgs e)
        {
            try
            {
                //Buscar Credenciais
                LCredenciais = objNegocioBackup.Autenticar();

                //AbreServiço
                LServico = objNegocioBackup.AbrirServico(LCredenciais);



                if (LCredenciais == null)
                {
                    lblStatus.Text = "Close";
                    return;
                }

                if (LServico == null)
                {
                    lblStatus.Text = "Close";
                    return;
                }

                lblStatus.Text = "Open";
            }
            catch (Exception)
            {
                MessageBox.Show("Erro ao conectar a api do Google Drive", "Erro", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                lblStatus.Text = "Close";
                return;
            }
        }
Example #6
0
        private void frmJunoSistema_Load(object sender, EventArgs e)
        {
            timer1.Enabled = true;

            if (JunoSystem.Properties.Settings.Default.GoogleDriveOption != "")
            {
                LGoogleDriveOption = JunoSystem.Properties.Settings.Default.GoogleDriveOption.ToString();
            }

            if (LGoogleDriveOption != "0")
            {
                ServiceDriveAPI objDriveApi = new ServiceDriveAPI();

                //Seach Credenciais
                LCredenciais = objDriveApi.Autenticar();

                //OpenService
                LServico = objDriveApi.AbrirServico(LCredenciais);

                if (LCredenciais == null || LServico == null)
                {
                    lblStatus.Text = "Connected";
                }
            }
        }
Example #7
0
        /// <summary>
        /// Procurar arquivo pelo nome e retornar as ID
        /// </summary>
        /// <returns> Retorna as Ids</returns>
        public string[] ProcurarArquivoId(Google.Apis.Drive.v3.DriveService servico, string nomeArquivo, bool procurarNaLixeira = false)
        {
            msgErro = "";
            var retorno = new List <string>();

            var request = servico.Files.List();

            request.Q = string.Format("name = '{0}'", nomeArquivo);
            if (!procurarNaLixeira)
            {
                request.Q += " and trashed = false";
            }
            request.Fields = "files(id)";
            var resultado = request.Execute();
            var arquivos  = resultado.Files;

            if (arquivos != null && arquivos.Any())
            {
                foreach (var arquivo in arquivos)
                {
                    retorno.Add(arquivo.Id);
                }
            }
            return(retorno.ToArray());
        }
Example #8
0
        public static void CreateFolderInFolder(string folderId, Google.Apis.Drive.v3.DriveService service)
        {
            // Google.Apis.Drive.v3.DriveService service = GetDriveService();

            var FileMetaData = new Google.Apis.Drive.v3.Data.File()
            {
                Name     = Path.GetFileName(OAuthConstants.PhotosFolderName),
                MimeType = "application/vnd.google-apps.folder",
                Parents  = new List <string>
                {
                    folderId
                }
            };


            Google.Apis.Drive.v3.FilesResource.CreateRequest request;

            request        = service.Files.Create(FileMetaData);
            request.Fields = "id";
            var file = request.Execute();

            LFLens.Helpers.Settings.PhotosFolderID = file.Id;

            var file1 = request;
        }
Example #9
0
        /// <summary>
        /// Updates the file to Google Drive.
        /// </summary>
        /// <param name="service"></param>
        /// <param name="uploadFile"></param>
        /// <param name="fileId"></param>
        /// <returns></returns>
        private static async Task <bool> UpdateFile(Google.Apis.Drive.v3.DriveService service, string uploadFile, string fileId)
        {
            if (System.IO.File.Exists(uploadFile))
            {
                var driveFile = new Google.Apis.Drive.v3.Data.File();
                driveFile.Name        = System.IO.Path.GetFileName(uploadFile);
                driveFile.Description = "Updated from TSChecker App";
                driveFile.MimeType    = GetMimeType(uploadFile);

                byte[] fileData = System.IO.File.ReadAllBytes(uploadFile);
                using (var memoryStream = new System.IO.MemoryStream(fileData))
                {
                    try
                    {
                        var request = service.Files.Update(driveFile, fileId, memoryStream, driveFile.MimeType);
                        await request.UploadAsync();

                        return(true);
                    }
                    catch
                    {
                        return(false);
                    }
                }
            }
            return(false);
        }
Example #10
0
        protected ImageFilter(Google.Apis.Drive.v3.DriveService service, string filename)
        {
            Google.Apis.Drive.v3.FilesResource.ListRequest findFilenameRequest = service.Files.List();
            findFilenameRequest.Fields = "files(id)";
            findFilenameRequest.Q      = "name = '" + filename + "'";
            IList <Google.Apis.Drive.v3.Data.File> filesList = findFilenameRequest.Execute().Files;

            TargetDirectoryId = filesList[0].Id;
        }
Example #11
0
        /// <summary>
        /// Cria Diretorio ou seja a pasta no Google Drive
        /// </summary>
        public void CriarDiretorio(Google.Apis.Drive.v3.DriveService servico, string nomeDiretorio)
        {
            msgErro = "";
            var diretorio = new Google.Apis.Drive.v3.Data.File();

            diretorio.Name     = nomeDiretorio;
            diretorio.MimeType = "application/vnd.google-apps.folder";
            var request = servico.Files.Create(diretorio);

            request.Execute();
        }
Example #12
0
        public GoogleDriveTracker(OAuth2Client client, string folderName)
        {
            _folderName = folderName ?? "";
            var initializer = new BaseClientService.Initializer
            {
                HttpClientInitializer = new HttpClientInitializer(client)
            };

            _service  = new Google.Apis.Drive.v3.DriveService(initializer);
            _folderId = GetFolderIdFromName(_folderName);
        }
Example #13
0
        public static void UpdateFolderName(string fileName, string fileId)
        {
            Google.Apis.Drive.v3.Data.File file = new Google.Apis.Drive.v3.Data.File()
            {
                Name = fileName
            };
            Google.Apis.Drive.v3.DriveService service = GetService_v3();
            var updateRequest = service.Files.Update(file, fileId);

            updateRequest.Fields = "name";
            file = updateRequest.Execute();
        }
Example #14
0
 public static void DeleteFile(string fileId)
 {
     try
     {
         Google.Apis.Drive.v3.DriveService service = GetService_v3();
         Google.Apis.Drive.v3.FilesResource.DeleteRequest DeleteRequest = service.Files.Delete(fileId);
         DeleteRequest.Execute();
     }
     catch (Exception ex)
     {
     }
 }
Example #15
0
        public static string GetSharableLink(string fileId)
        {
            string link = "";

            Google.Apis.Drive.v3.DriveService service = GetService_v3();
            // Define parameters of request.
            Google.Apis.Drive.v3.FilesResource.ListRequest FileListRequest = service.Files.List();
            FileListRequest.Fields = "files(id, webViewLink)";
            // List files.
            IList <Google.Apis.Drive.v3.Data.File> files = FileListRequest.Execute().Files;

            link = files.Where(x => x.Id == fileId).FirstOrDefault().WebViewLink;
            return(link);
        }
Example #16
0
        /// <summary>
        /// Download Google drive
        /// </summary>
        /// <param name="servico"></param>
        /// <param name="nome"></param>
        /// <param name="destino"></param>
        public void Download(Google.Apis.Drive.v3.DriveService servico, string nome, string destino)
        {
            msgErro = "";
            var ids = ProcurarArquivoId(servico, nome);

            if (ids != null && ids.Any())
            {
                var request = servico.Files.Get(ids.First());
                using (var stream = new System.IO.FileStream(destino, System.IO.FileMode.Create, System.IO.FileAccess.Write))
                {
                    request.Download(stream);
                }
            }
        }
        public static void CreateFolder(string FolderName)
        {
            Google.Apis.Drive.v3.DriveService service = GetService_v3();

            Google.Apis.Drive.v3.Data.File FileMetaData = new Google.Apis.Drive.v3.Data.File();
            FileMetaData.Name     = FolderName;
            FileMetaData.MimeType = "application/vnd.google-apps.folder";

            Google.Apis.Drive.v3.FilesResource.CreateRequest request;

            request        = service.Files.Create(FileMetaData);
            request.Fields = "id";
            var file = request.Execute();
            //Console.WriteLine("Folder ID: " + file.Id);
        }
Example #18
0
        public static void CreateAppFolder(string FolderName, Google.Apis.Drive.v3.DriveService service)
        {
//            Google.Apis.Drive.v3.DriveService service = GetDriveService();

            var FileMetaData = new Google.Apis.Drive.v3.Data.File();

            FileMetaData.MimeType = "application/vnd.google-apps.folder";
            FileMetaData.Name     = FolderName;
            Google.Apis.Drive.v3.FilesResource.CreateRequest request;
            request        = service.Files.Create(FileMetaData);
            request.Fields = "id";
            var file = request.Execute();

            GoogleDriveFiles.CreateFolderInFolder(file.Id, service);
        }
Example #19
0
        public static string FileUploadInFolder(string folderId, HttpPostedFile file, string fileName, string mimeType)
        {
            try
            {
                Google.Apis.Drive.v3.DriveService service = GetService_v3();

                var FileMetaData = new Google.Apis.Drive.v3.Data.File()
                {
                    Name     = fileName,
                    MimeType = mimeType,
                    Parents  = new List <string>
                    {
                        folderId
                    }
                };


                string path = HttpContext.Current.Server.MapPath("~/QuotePurposeAttachments/");
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }

                string filePath = Path.Combine(path, Path.GetFileName(file.FileName));


                file.SaveAs(filePath);

                Google.Apis.Drive.v3.FilesResource.CreateMediaUpload request;

                using (var stream = new System.IO.FileStream(filePath, System.IO.FileMode.Open))
                {
                    request        = service.Files.Create(FileMetaData, stream, FileMetaData.MimeType);
                    request.Fields = "id";
                    request.Upload();
                }

                System.IO.File.Delete(filePath);


                var file1 = request.ResponseBody;
                return(file1.Id);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Example #20
0
        /// <summary>
        /// Enviar arquivo para lixeira, não vai excluir por meio de segurança. caso o bakup que foi enviado não esteja correto, ele não
        /// </summary>
        /// <param name="servico"></param>
        /// <param name="nome"></param>
        public void MoverParaLixeira(Google.Apis.Drive.v3.DriveService servico, string nome)
        {
            msgErro = "";
            var ids = ProcurarArquivoId(servico, nome);

            if (ids != null && ids.Any())
            {
                foreach (var id in ids)
                {
                    var arquivo = new Google.Apis.Drive.v3.Data.File();
                    arquivo.Trashed = true;
                    var request = servico.Files.Update(arquivo, id);
                    request.Execute();
                }
            }
        }
Example #21
0
        public static Google.Apis.Drive.v3.DriveService GetService_v3()
        {
            string         path = HttpContext.Current.Server.MapPath("~/App_Data/");
            UserCredential credential;

            using (var stream = new FileStream(path + "credentials.json", FileMode.Open, FileAccess.Read))
            {
                //String FolderPath = @"D:\";
                String FolderPath = HttpContext.Current.Server.MapPath("~");
                String FilePath   = Path.Combine(FolderPath, "DriveServiceCredentials.json");

                credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                    GoogleClientSecrets.Load(stream).Secrets,
                    Scopes,
                    "user",
                    CancellationToken.None,
                    new FileDataStore(FilePath, true)).Result;
            }

            //Create Drive API service.
            Google.Apis.Drive.v3.DriveService service = new Google.Apis.Drive.v3.DriveService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName       = "GoogleDriveRestAPI-v3",
            });

            //Service Account
            //string path = HttpContext.Current.Server.MapPath("~/App_Data/");
            //var keyFilePath = path + "Quickstart-7181e72973ec.p12";    // Downloaded from https://console.developers.google.com
            //var serviceAccountEmail = "*****@*****.**";  // found https://console.developers.google.com

            ////loading the Key file
            //var certificate = new X509Certificate2(keyFilePath, "notasecret", X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable);
            //var credential = new ServiceAccountCredential(new ServiceAccountCredential.Initializer(serviceAccountEmail)
            //{
            //    Scopes = Scopes
            //}.FromCertificate(certificate));
            //Google.Apis.Drive.v3.DriveService service = new Google.Apis.Drive.v3.DriveService(new BaseClientService.Initializer()
            //{
            //    HttpClientInitializer = credential,
            //    ApplicationName = "Quickstart-3",

            //});
            //
            return(service);
        }
Example #22
0
        /// <summary>
        /// Deletar Item
        /// </summary>
        /// <param name="servico"></param>
        /// <param name="nome"></param>
        public void DeletarItem(Google.Apis.Drive.v3.DriveService servico, string nome)
        {
            msgErro = "";
            var ids = ProcurarArquivoId(servico, nome);

            if (ids != null && ids.Any())
            {
                foreach (var id in ids)
                {
                    try
                    {
                        var request = servico.Files.Delete(id);
                        request.Execute();
                    }
                    catch (Exception)
                    {
                        msgErro = "Erro o Excluir Arquivo (Permissão, Arquivo Inexiste!";
                    }
                }
            }
        }
Example #23
0
        /// <summary>
        /// Downloads the file from Google Drive.
        /// </summary>
        /// <param name="service"></param>
        /// <param name="file"></param>
        /// <returns></returns>
        private static async Task <byte[]> DownloadFile(Google.Apis.Drive.v3.DriveService service, string fileId)
        {
            if (!string.IsNullOrEmpty(fileId))
            {
                try
                {
                    var request = service.Files.Get(fileId);
                    using (var memoryStream = new System.IO.MemoryStream())
                    {
                        await request.DownloadAsync(memoryStream);

                        return(memoryStream.ToArray());
                    }
                }
                catch
                {
                    return(null);
                }
            }
            return(null);
        }
        public bool ValidateCredential()
        {
            var res = true;

            try
            {
                Google.Apis.Auth.OAuth2.UserCredential credential =
                    Google.Apis.Auth.OAuth2.GoogleWebAuthorizationBroker.AuthorizeAsync(
                        new Google.Apis.Auth.OAuth2.ClientSecrets
                {
                    ClientId     = googleDriverParam.ClientId,
                    ClientSecret = googleDriverParam.ClientSecret,
                },
                        new[] { Google.Apis.Drive.v3.DriveService.Scope.Drive },
                        "user",
                        System.Threading.CancellationToken.None).Result;

                userCredential = credential;

                var service = new Google.Apis.Drive.v3.DriveService(new Google.Apis.Services.BaseClientService.Initializer()
                {
                    HttpClientInitializer = userCredential,
                    ApplicationName       = googleDriverParam.ApplicationName
                });

                driveService = service;
                Validated    = true;
            }
            catch (Exception e)
            {
                Validated         = false;
                ValidationMessage = e.Message;
                res = false;
            }
            finally
            {
            }

            return(res);
        }
Example #25
0
        public static Google.Apis.Drive.v3.DriveService GetDriveService()
        {
            Google.Apis.Drive.v3.DriveService service = new Google.Apis.Drive.v3.DriveService();

            Google.Apis.Auth.OAuth2.Flows.GoogleAuthorizationCodeFlow googleAuthFlow = new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer()
            {
                ClientSecrets = new ClientSecrets()
                {
                    ClientId     = OAuthConstants.GoogleAndroidClientId,
                    ClientSecret = null,
                }
            });

            Google.Apis.Auth.OAuth2.Responses.TokenResponse responseToken = new TokenResponse()
            {
                AccessToken = LFLens.Helpers.Settings.AccessToken,

                RefreshToken = LFLens.Helpers.Settings.RefreshToken,
                Scope        = OAuthConstants.GoogleScope,
                TokenType    = "Bearer",
            };

            var credential = new UserCredential(googleAuthFlow, "", responseToken);



            //Once consent is recieved, your token will be stored locally on the AppData directory, so that next time you wont be prompted for consent.

            service = new Google.Apis.Drive.v3.DriveService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName       = OAuthConstants.AppName,
            });
            service.HttpClient.Timeout = TimeSpan.FromMinutes(100);


            //  else { await Navigation.PushModalAsync(new NavigationPage(new OAuth())); }

            return(service);
        }
Example #26
0
        public static void CreateFolder(string FolderName, ref string folderId, string parent)
        {
            Google.Apis.Drive.v3.DriveService service = GetService_v3();

            Google.Apis.Drive.v3.Data.File FileMetaData = new Google.Apis.Drive.v3.Data.File();
            FileMetaData.Name     = FolderName;
            FileMetaData.MimeType = "application/vnd.google-apps.folder";
            //idfolder of shared folder in gg drive
            FileMetaData.Parents = new List <string> {
                parent
            };

            Google.Apis.Drive.v3.FilesResource.CreateRequest request;

            request                    = service.Files.Create(FileMetaData);
            request.Fields             = "id";
            request.SupportsTeamDrives = true;
            var file = request.Execute();

            //Console.WriteLine("Folder ID: " + file.Id);
            folderId = file.Id;
        }
Example #27
0
        //author:Vamsi
        //date: 20/03/2020
        //To save invoice file to google drive
        public static string UploadInvoiceFiletoGoogleDrivefolder(string folderId, string fileName, byte[] invoicedoc)
        {
            try
            {
                Google.Apis.Drive.v3.DriveService service = GetService_v3();
                var FileMetaData = new Google.Apis.Drive.v3.Data.File()
                {
                    Name     = fileName,
                    MimeType = null,
                    Parents  = new List <string>
                    {
                        HelperMethods.Literals.GDriveInvoicegFolderId
                    }
                };
                string path = HttpContext.Current.Server.MapPath("~/QuotePurposeAttachments/");
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }
                string filePath = Path.Combine(path, Path.GetFileName(fileName + ".pdf"));
                System.IO.File.WriteAllBytes(filePath, invoicedoc);
                Google.Apis.Drive.v3.FilesResource.CreateMediaUpload request;

                using (var stream = new System.IO.FileStream(filePath, System.IO.FileMode.Open))
                {
                    request        = service.Files.Create(FileMetaData, stream, FileMetaData.MimeType);
                    request.Fields = "id";
                    request.Upload();
                }
                System.IO.File.Delete(filePath);
                var file1 = request.ResponseBody;
                return(file1.Id);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Example #28
0
 public static bool CheckFileExists(string fileId)
 {
     try
     {
         if (fileId != null)
         {
             Google.Apis.Drive.v3.DriveService service = GetService_v3();
             var file = service.Files.Get(fileId).Execute();
             if (file.Trashed == true)
             {
                 var data = file.Trashed;
             }
             if (file.Name != null || file.Name != "")
             {
                 return(true);
             }
             else
             {
                 return(false);
             }
         }
         else
         {
             return(false);
         }
     }
     catch (Exception ex)
     {
         if (ex.Message.Contains("404") == true)
         {
             return(false);
         }
         else
         {
             throw ex;
         }
     }
 }
Example #29
0
        public static string CreateFolder(string FolderName, string parentId)
        {
            try
            {
                Google.Apis.Drive.v3.DriveService service = GetService_v3();

                var FileMetaData = new Google.Apis.Drive.v3.Data.File();
                FileMetaData.Name     = FolderName;
                FileMetaData.MimeType = "application/vnd.google-apps.folder";
                if (parentId != null)
                {
                    FileMetaData.Parents = new List <string> {
                        parentId
                    };
                }
                Google.Apis.Drive.v3.FilesResource.CreateRequest request;

                request        = service.Files.Create(FileMetaData);
                request.Fields = "id";
                var file = request.Execute();

                //Google.Apis.Drive.v3.Data.File file = request.ResponseBody;
                //Google.Apis.Drive.v2.Data.Permission newPermission = new Google.Apis.Drive.v2.Data.Permission();
                //newPermission.Value = "*****@*****.**";
                //newPermission.Type = "user";
                //newPermission.Role = "writer";

                //Google.Apis.Drive.v2.PermissionsResource.InsertRequest insertRequest = GetService_v2().Permissions.Insert(newPermission, file.Id);
                //insertRequest.SendNotificationEmails = false;
                //insertRequest.Execute();
                //Console.WriteLine("Folder ID: " + file.Id);
                return(file.Id);
            }
            catch (Exception ex)
            {
                throw;
            }
        }
Example #30
0
        public static string FileUploadInFolder(string folderId, string filePath, string fileName)
        {
            string fileId = string.Empty;

            try
            {
                if (System.IO.File.Exists(filePath))
                {
                    Google.Apis.Drive.v3.DriveService service = GetService_v3();

                    //string path = Path.Combine(HttpContext.Current.Server.MapPath("~/GoogleDriveFiles"),
                    //Path.GetFileName(file.FileName));
                    //file.SaveAs(path);

                    var FileMetaData = new Google.Apis.Drive.v3.Data.File()
                    {
                        Name     = string.IsNullOrEmpty(fileName) ? Path.GetFileName(filePath) : fileName,
                        MimeType = MimeMapping.GetMimeMapping(filePath)
                    };

                    Google.Apis.Drive.v3.FilesResource.CreateMediaUpload request;
                    using (var stream = new System.IO.FileStream(filePath, System.IO.FileMode.Open))
                    {
                        request        = service.Files.Create(FileMetaData, stream, FileMetaData.MimeType);
                        request.Fields = "id";
                        request.Upload();
                    }
                    var file1 = request.ResponseBody;
                    fileId = file1.Id;
                }
            }
            catch (Exception)
            {
                throw;
            }
            return(fileId);
        }