//get all files from Google Drive. public static List <GoogleDriveFiles> GetDriveFiles() { Google.Apis.Drive.v3.DriveService service = GetService(); // define parameters of request. Google.Apis.Drive.v3.FilesResource.ListRequest FileListRequest = service.Files.List(); //listRequest.PageSize = 10; //listRequest.PageToken = 10; FileListRequest.Fields = "nextPageToken, files(createdTime, id, name, size, version, trashed, parents)"; //get file list. 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); }
private static void backgroundWorker1_DoWork() //подключение к диску и загрузка файлов { // object sender, DoWorkEventArgs e UserCredential credential; try { //download = new List<string>();//коллеция ссылок для загрузки FileStream str = new FileStream("client_secret.json", FileMode.Open, FileAccess.Read); using (FileStream stream = new FileStream("client_secret.json", FileMode.Open, FileAccess.Read))// создание потока для чтения client_secret.json { string credPath = System.Environment.GetFolderPath( System.Environment.SpecialFolder.Personal); credPath = Path.Combine(credPath, ".credentials/drive-dotnet-quickstart.json");//путь к файлу управления подключением credential = GoogleWebAuthorizationBroker.AuthorizeAsync( GoogleClientSecrets.Load(stream).Secrets, Scopes, GoogleClientSecrets.Load(str).Secrets.ClientId, CancellationToken.None, new FileDataStore(credPath, true)).Result; var service = new Google.Apis.Drive.v3.DriveService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = ApplicationName, }); str.Close(); // Define parameters of request. Google.Apis.Drive.v3.FilesResource.ListRequest listRequest = service.Files.List(); listRequest.PageSize = 400; listRequest.Fields = "nextPageToken, files(id, webViewLink, webContentLink, name, size, mimeType)";//требуемые свойства загружаемых файлов(можно убрать лишнее или добавить требуемое) // List files. IList <Google.Apis.Drive.v3.Data.File> files = listRequest.Execute() .Files; Console.WriteLine("Files:"); if (files != null && files.Count > 0) { foreach (var file in files) { if (file.Name == "базы" || file.Name == "нормативы") { continue; } Console.WriteLine(" {0} (Size: {1} КБ)", file.Name, file.Size / 1000.0); } } else { Console.WriteLine("No files found."); } Console.ReadLine(); } } catch (Exception x) { Console.WriteLine(x.Message); Console.Read(); } Console.ReadLine(); }
private void DownloadFiles() { var backoff = 1000; Google.Apis.Services.BaseClientService.Initializer bcs = new Google.Apis.Services.BaseClientService.Initializer(); bcs.ApiKey = settings.ApiKey; bcs.ApplicationName = "Intersect Updater"; bcs.GZipEnabled = true; Google.Apis.Drive.v3.DriveService service = new Google.Apis.Drive.v3.DriveService(bcs); while (!UpdateList.IsEmpty) { Update update; if (UpdateList.TryDequeue(out update)) { if (DownloadUpdate(service, update)) { } else { //Back off UpdateList.Enqueue(update); backoff = backoff * 2; System.Threading.Thread.Sleep(backoff); } } } }
//create Drive API service. public static DriveService GetService() { //get Credentials from client_secret.json file UserCredential credential; //Root Folder of project var CSPath = System.Web.Hosting.HostingEnvironment.MapPath("~/"); using (var stream = new FileStream(Path.Combine(CSPath, "credentials.json"), FileMode.Open, FileAccess.Read)) { String FolderPath = System.Web.Hosting.HostingEnvironment.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. DriveService service = new Google.Apis.Drive.v3.DriveService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = "GoogleDriveMVCUpload", }); return(service); }
//create Drive API service. public static Google.Apis.Drive.v3.DriveService GetService() { //get Credentials from client_secret.json file UserCredential credential; using (var stream = new FileStream(@"C:\client_secret.json", FileMode.Open, FileAccess.Read)) { String FolderPath = @"C:\"; 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); }
public static void CredentialDriveServiceByToken() { if (DriveService == null) { UserCredential credential; using (var stream = new FileStream(credentialPath, FileMode.Open, FileAccess.Read)) { string credPath = "token.json"; credential = GoogleWebAuthorizationBroker.AuthorizeAsync( GoogleClientSecrets.Load(stream).Secrets, new string[] { DriveService.Scope.DriveReadonly }, "user", CancellationToken.None, new FileDataStore(credPath, true)).Result; Console.WriteLine("Credential file saved to: " + credPath); } // Create Drive API service. var service = new DriveService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = ApplicationName, }); DriveService = service; DriveManager.Init(service); } }
/// <summary> /// returns all files from drive /// </summary> /// <returns></returns> public List <GoogleDriveFile> GetDriveFiles() { Google.Apis.Drive.v3.DriveService service = GetService(); // Define parameters of request. Google.Apis.Drive.v3.FilesResource.ListRequest FileListRequest = service.Files.List(); // for getting folders only. //FileListRequest.Q = "mimeType='application/vnd.google-apps.folder'"; FileListRequest.Fields = "nextPageToken, files(*)"; // List files. IList <Google.Apis.Drive.v3.Data.File> files = FileListRequest.Execute().Files; List <GoogleDriveFile> FileList = new List <GoogleDriveFile>(); // For getting only folders // files = files.Where(x => x.MimeType == "application/vnd.google-apps.folder ").ToList(); if (files != null && files.Count > 0) { foreach (var file in files) { GoogleDriveFile File = new GoogleDriveFile { Id = file.Id, Name = file.Name, Size = file.Size, Version = file.Version, CreatedTime = file.CreatedTime, Parents = file.Parents, MimeType = file.MimeType }; FileList.Add(File); } } return(FileList); }
private void CreateAppFolder() { Google.Apis.Drive.v3.DriveService service = GoogleDriveFiles.GetDriveService(); bool isRootFolderExists = GoogleDriveFiles.CheckFolder(OAuthConstants.AppName, service); if (isRootFolderExists == false) { GoogleDriveFiles.CreateAppFolder(OAuthConstants.AppName, service); } FilesResource.ListRequest listRequest = service.Files.List(); IList <Google.Apis.Drive.v3.Data.File> mfiles = listRequest.Execute().Files; foreach (var file in mfiles) { if (file.Name == OAuthConstants.AppName) { LFLens.Helpers.Settings.RootFolderID = file.Id; } if (file.Name == OAuthConstants.PhotosFolderName) { LFLens.Helpers.Settings.PhotosFolderID = file.Id; } } }
public static Google.Apis.Drive.v3.DriveService TesteService() { try { String serviceAccountEmail = "*****@*****.**"; var certificate = new X509Certificate2(@"servicesceltainfra-6f1e21301fbe.p12", "notasecret", X509KeyStorageFlags.Exportable); ServiceAccountCredential credential = new ServiceAccountCredential( new ServiceAccountCredential.Initializer(serviceAccountEmail) { Scopes = new[] { "https://www.googleapis.com/auth/drive" } }.FromCertificate(certificate)); // Create the service. var service = new Google.Apis.Drive.v3.DriveService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = "Service infra", }); return(service); } catch (Exception err) { throw err; } }
public static void CreateFolderInFolder(string folderId, string FolderName) { Google.Apis.Drive.v3.DriveService service = GetService(); var FileMetaData = new Google.Apis.Drive.v3.Data.File() { Name = Path.GetFileName(FolderName), 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(); Console.WriteLine("Folder ID: " + file.Id); var file1 = request; }
//file Upload to the Google Drive. public static string FileUploadInFolder(string folderId, HttpPostedFileBase file) { FilesResource.CreateMediaUpload request = null; if (file != null && file.ContentLength > 0) { Google.Apis.Drive.v3.DriveService service = GetService(); 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 } }; 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(); } } return(request.ResponseBody.Id.ToString()); }
private static void DownloadFile(Google.Apis.Drive.v3.DriveService service, Google.Apis.Drive.v3.Data.File file, string saveTo) { var request = service.Files.Get(file.Id); var stream = new System.IO.MemoryStream(); request.MediaDownloader.ProgressChanged += (Google.Apis.Download.IDownloadProgress progress) => { switch (progress.Status) { case Google.Apis.Download.DownloadStatus.Downloading: { Console.WriteLine(progress.BytesDownloaded); break; } case Google.Apis.Download.DownloadStatus.Completed: { Console.WriteLine("Download complete."); SaveStreamto(stream, saveTo); break; } case Google.Apis.Download.DownloadStatus.Failed: { Console.WriteLine("Download failed."); break; } } }; request.Download(stream); }
public static Google.Apis.Drive.v3.DriveService GetService_v3() { UserCredential credential; String baseDir = AppDomain.CurrentDomain.BaseDirectory; String configPath = Path.Combine(baseDir, "./../../../../credentials.json"); //Console.WriteLine(configPath); using (var stream = new FileStream(configPath, FileMode.Open, FileAccess.Read)) { string credPath = System.Environment.GetFolderPath( System.Environment.SpecialFolder.Personal); credPath = System.IO.Path.Combine(credPath, ".credentials/token.json"); credential = GoogleWebAuthorizationBroker.AuthorizeAsync( GoogleClientSecrets.Load(stream).Secrets, Scopes, "user", CancellationToken.None, new FileDataStore(credPath, 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); }
public static Google.Apis.Drive.v3.DriveService GetService_v3() { UserCredential credential; var auth_filename = AppConfiguration.GetAppConfig("CredentialPath"); using (var stream = new FileStream(auth_filename, FileMode.Open, FileAccess.Read)) { //String FolderPath = @"D:\"; //String FilePath = Path.Combine(FolderPath, "DriveServiceCredentials.json"); var authPath = Path.GetDirectoryName(Application.ExecutablePath) + "\\Authentication\\"; credential = GoogleWebAuthorizationBroker.AuthorizeAsync( GoogleClientSecrets.Load(stream).Secrets, Scopes, "user", CancellationToken.None, new FileDataStore(authPath, true)).Result; } //Create Drive API service. Google.Apis.Drive.v3.DriveService service = new Google.Apis.Drive.v3.DriveService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = "SuchPropsUploader", }); return(service); }
public static string getBackupFolderId(string FolderName) { 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 }; if (file.Name.Equals(FolderName)) { return(file.Id); } } } return(string.Empty); }
//file Upload to the Google Drive root folder. public static void FileUpload(HttpPostedFileBase file) { if (file != null && file.ContentLength > 0) { Google.Apis.Drive.v3.DriveService service = GetService(); 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(); FileMetaData.Name = Path.GetFileName(file.FileName); FileMetaData.MimeType = MimeMapping.GetMimeMapping(path); 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(); } // Create Folder in Drive } }
//create Drive API service. public DriveService GetService() { //get Credentials from client_secret.json file UserCredential credential; //Root Folder of project string folderName = "Credentials"; string webRootPath = _webHostEnvironment.WebRootPath; string newPath = Path.Combine(webRootPath, folderName); string filename = Path.Combine(newPath, "client_secret_263519154515-3at0qlc6fsh90fo4jhjr6vr8sprok7qv.apps.googleusercontent.com.json"); using (var stream = new FileStream(filename, FileMode.Open, FileAccess.Read)) { string credPath = newPath; //string credPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal); credPath = Path.Combine(newPath, "DriveServiceCredentials.json"); credential = GoogleWebAuthorizationBroker.AuthorizeAsync( GoogleClientSecrets.Load(stream).Secrets, Scopes, "user", CancellationToken.None, new FileDataStore(credPath, true)).Result; } //create Drive API service. DriveService service = new Google.Apis.Drive.v3.DriveService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = "NYSCFileRecord", }); return(service); }
// File upload in existing folder public static void FileUploadInFolder(string folderId, System.IO.FileStream file) { if (file != null && file.Length > 0) { Google.Apis.Drive.v3.DriveService service = GetService(); string path = Path.Combine(HttpContext.Current.Server.MapPath("~/GDrive"), Path.GetFileName(file.Name)); var FileMetaData = new Google.Apis.Drive.v3.Data.File() { Name = Path.GetFileName(file.Name), MimeType = MimeMapping.GetMimeMapping(path), Parents = new List <string> { folderId } }; file.Close(); 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 DriveService GetService() { UserCredential credential; //Root Folder of project var CSPath = _env.ContentRootPath; using (var stream = new FileStream(Path.Combine(CSPath, "googleDriveCredential.json"), FileMode.Open, FileAccess.Read)) { String FolderPath = _env.ContentRootPath; 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. DriveService service = new Google.Apis.Drive.v3.DriveService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = "ReadPDF", }); return(service); }
public static Google.Apis.Drive.v3.DriveService GetGoogleService(string authType) { Google.Apis.Drive.v3.DriveService service = null; if (authType == "service") { // Load the Service account credentials and define the scope of its access. var credential = GoogleCredential.FromFile("mydriveapiproject-310118-90ab749df59c.json") .CreateScoped(DriveService.ScopeConstants.Drive); service = new DriveService(new BaseClientService.Initializer() { HttpClientInitializer = credential }); } else if (authType == "apikey") { Google.Apis.Services.BaseClientService.Initializer bcs = new Google.Apis.Services.BaseClientService.Initializer(); bcs.ApiKey = "AIzaSyCOes0NQs2UyWdD3AcrsX60fQ1xl5h9Xk0"; bcs.ApplicationName = "MyDriveAPIProjectKey"; service = new DriveService(bcs); } return(service); }
//create Drive API service. public DriveService GetService() { //get Credentials from client_secret.json file UserCredential credential; //Root Folder of project using (var stream = new FileStream("credentials.json", FileMode.Open, FileAccess.Read)) { string credPath = _webHostEnvironment.WebRootPath; //string credPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal); credPath = Path.Combine(credPath, "credentials.json"); credential = GoogleWebAuthorizationBroker.AuthorizeAsync( GoogleClientSecrets.Load(stream).Secrets, Scopes, "user", CancellationToken.None, new FileDataStore(credPath, true)).Result; } //create Drive API service. DriveService service = new Google.Apis.Drive.v3.DriveService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = "NYSCFileRecord", }); return(service); }
public string MoveFiles(String fileId, String folderId) { Google.Apis.Drive.v3.DriveService service = GetService(); // Retrieve the existing parents to remove Google.Apis.Drive.v3.FilesResource.GetRequest getRequest = service.Files.Get(fileId); getRequest.Fields = "parents"; Google.Apis.Drive.v3.Data.File file = getRequest.Execute(); string previousParents = String.Join(",", file.Parents); // Move the file to the new folder Google.Apis.Drive.v3.FilesResource.UpdateRequest updateRequest = service.Files.Update(new Google.Apis.Drive.v3.Data.File(), fileId); updateRequest.Fields = "id, parents"; updateRequest.AddParents = folderId; updateRequest.RemoveParents = previousParents; file = updateRequest.Execute(); if (file != null) { return("Success"); } else { return("Fail"); } }
public static void Download(Google.Apis.Drive.v3.DriveService service, Google.Apis.Drive.v3.Data.File file, string saveTo) { var request = service.Files.Get(file.Id); var stream = new System.IO.MemoryStream(); // Add a handler which will be notified on progress changes. // It will notify on each chunk download and when the // download is completed or failed. request.MediaDownloader.ProgressChanged += (Google.Apis.Download.IDownloadProgress progress) => { switch (progress.Status) { case Google.Apis.Download.DownloadStatus.Downloading: { status = Convert.ToString(progress.BytesDownloaded); break; } case Google.Apis.Download.DownloadStatus.Completed: { status = ("Download complete."); SaveStream(stream, saveTo); break; } case Google.Apis.Download.DownloadStatus.Failed: { status = ("Download failed."); break; } } }; request.Download(stream); }
// create sharing folder public static string CreateFolderWithSharingPermission(string FolderName /*, string EmailAddress, string UserRole*/) { try { //Create Folder in Google Drive Google.Apis.Drive.v3.DriveService service = GetService(); var fileMetadata = new Google.Apis.Drive.v3.Data.File() { Name = FolderName, MimeType = "application/vnd.google-apps.folder", Description = "File_" + System.DateTime.Now.Hour + ":" + System.DateTime.Now.Minute + ":" + System.DateTime.Now.Second }; Google.Apis.Drive.v3.FilesResource.CreateRequest request = service.Files.Create(fileMetadata); request.Fields = "id"; string Fileid = request.Execute().Id; Google.Apis.Drive.v3.Data.Permission permission = new Google.Apis.Drive.v3.Data.Permission(); permission.Type = "anyone"; // sharing permission //permission.EmailAddress = EmailAddress; permission.Role = "writer"; //all type of permission but not allow for delete file &folders permission = service.Permissions.Create(permission, Fileid).Execute(); //if (UserRole == "writer" || UserRole == "reader") //{ // permission.Type = "anyone"; // permission.EmailAddress = EmailAddress; // permission.Role = UserRole; // permission = service.Permissions.Create(permission, Fileid).Execute(); //} //else if (UserRole == "owner") //{ // permission.Type = "user"; // permission.EmailAddress = EmailAddress; // permission.Role = UserRole; // Google.Apis.Drive.v3.PermissionsResource.CreateRequest createRequestPermission = service.Permissions.Create(permission, Fileid); // createRequestPermission.TransferOwnership = true; // createRequestPermission.Execute(); //} if (permission != null) { return(Fileid); } else { return("error"); } } catch (Exception e) { return("An error occurred: " + e.Message); } }
private static void CreateFolder(Google.Apis.Drive.v3.DriveService service, string directoryName) { var diretorio = new Google.Apis.Drive.v3.Data.File(); diretorio.Name = directoryName; diretorio.MimeType = "application/vnd.google-apps.folder"; var request = service.Files.Create(diretorio); request.Execute(); }
// Create Folder in root public static void CreateFolder(string FolderName) { Google.Apis.Drive.v3.DriveService service = GetService(); var 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); }
public static void CreateFolderOnDrive(string Folder_Name) { Google.Apis.Drive.v3.DriveService service = GetGoogleService("service"); Google.Apis.Drive.v3.Data.File FileMetaData = new Google.Apis.Drive.v3.Data.File(); FileMetaData.Name = Folder_Name; 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(); }
// Display list audio public static List <GoogleDriveFiles> Index() { Google.Apis.Drive.v3.DriveService service = GetService(); // define parameters of request. Google.Apis.Drive.v3.FilesResource.ListRequest FileListRequest = service.Files.List(); //listRequest.PageSize = 10; //listRequest.PageToken = 10; FileListRequest.Fields = "nextPageToken, files(createdTime, id, name, size, version, trashed, parents)"; //get file list. 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 }; string path = Path.Combine(HttpContext.Current.Server.MapPath("~"), Path.GetFileName(file.Name)); var fileMETA = new Google.Apis.Drive.v3.Data.File() { Name = file.Name, MimeType = MimeMapping.GetMimeMapping(path) }; if (fileMETA.MimeType == "audio/mpeg" || fileMETA.MimeType == "audio/wav") { FileList.Add(File); } } } return(FileList); }
// upload file in folder public static async Task <string> FileUploadInFolder(string folderId, HttpPostedFile file) { try { if (file != null && file.ContentLength > 0) { Google.Apis.Drive.v3.DriveService service = GetService(); var subPath = "~/GoogleDriveFiles"; bool exists = System.IO.Directory.Exists(HttpContext.Current.Server.MapPath(subPath)); if (!exists) { System.IO.Directory.CreateDirectory(HttpContext.Current.Server.MapPath(subPath)); } string path = Path.Combine(HttpContext.Current.Server.MapPath(subPath), 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"; await request.UploadAsync(); } var file1 = request.ResponseBody; File.Delete(path); return(file1.Id); } return(null); } catch (Exception) { return(null); } }
public static List <Google.Apis.Drive.v3.Data.File> GetDriveFiles2(string folderID) { Google.Apis.Drive.v3.DriveService service = GetGoogleService("service"); Google.Apis.Drive.v3.FilesResource.ListRequest listRequest = service.Files.List(); //listRequest.Q = "'" + folderID + "' in parents"; listRequest.Q = "mimeType='application/vnd.google-apps.folder'"; listRequest.PageSize = 10; listRequest.Fields = "nextPageToken, files(id, name)"; IList <Google.Apis.Drive.v3.Data.File> files = listRequest.Execute().Files; var counter = files.Count(); return(files.ToList()); }