Exemple #1
0
        public static List <GoogleDriveFiles> GetContainsInFolder(String folderId)
        {
            List <string> ChildList = new List <string>();

            Google.Apis.Drive.v2.DriveService ServiceV2          = GetService_v2();
            ChildrenResource.ListRequest      ChildrenIDsRequest = ServiceV2.Children.List(folderId);
            do
            {
                ChildList children = ChildrenIDsRequest.Execute();

                if (children.Items != null && children.Items.Count > 0)
                {
                    foreach (var file in children.Items)
                    {
                        ChildList.Add(file.Id);
                    }
                }
                ChildrenIDsRequest.PageToken = children.NextPageToken;
            } while (!String.IsNullOrEmpty(ChildrenIDsRequest.PageToken));

            //Get All File List
            List <GoogleDriveFiles> AllFileList     = GetDriveFiles();
            List <GoogleDriveFiles> Filter_FileList = new List <GoogleDriveFiles>();

            foreach (string Id in ChildList)
            {
                Filter_FileList.Add(AllFileList.Where(x => x.Id == Id).FirstOrDefault());
            }
            return(Filter_FileList);
        }
Exemple #2
0
        // Get files from the specified drive folder.
        private void GetFilesFromDriveMethod()
        {
            // Request all the children of the specified folder.
            ChildrenResource.ListRequest listRequest = DriveService.Children.List(DriveFolderId);

            do
            {
                try
                {
                    // Execute the child list request.
                    ChildList children = listRequest.Execute();

                    foreach (ChildReference child in children.Items)
                    {
                        driveFileVMs.Add(new DriveFileVM(child, DriveService));
                    }

                    // set the token for the next page of the request.
                    listRequest.PageToken = children.NextPageToken;
                }
                catch (Exception ex)
                {
                    listRequest.PageToken = null;
                }
            } while (!String.IsNullOrEmpty(listRequest.PageToken));
        }
Exemple #3
0
        private static void GoogleDir(DriveService service, string folderId, string path)
        {
            try
            {
                ChildrenResource.ListRequest request = service.Children.List(folderId);
                request.MaxResults = 1000;

                do
                {
                    ChildList children = request.Execute();

                    foreach (ChildReference child in children.Items)
                    {
                        File file = service.Files.Get(child.Id).Execute();
                        if (file.MimeType == "application/vnd.google-apps.folder")
                        {
                            GoogleDir(service, file.Id, @"\" + path + @"\" + file.Title);
                        }
                        else
                        {
                        }

                        Console.WriteLine("Title: " + file.Title);

                        Console.WriteLine("MIME type: " + file.MimeType);
                        Console.WriteLine();
                    }
                    request.PageToken = children.NextPageToken;
                } while (!String.IsNullOrEmpty(request.PageToken));
            }
            catch (Exception)
            {
                throw;
            }
        }
        public static string GetFolderID(DriveService service, String parentfolderId, string FolderName)
        {
            ChildrenResource.ListRequest request = service.Children.List(parentfolderId);
            request.Q = "mimeType='application/vnd.google-apps.folder' and title='" + FolderName + "' ";
            do
            {
                try
                {
                    ChildList children = request.Execute();

                    if (children != null && children.Items.Count > 0)
                    {
                        return(children.Items[0].Id);
                    }

                    foreach (ChildReference child in children.Items)
                    {
                        Console.WriteLine("File Id: " + child.Id);
                    }
                    request.PageToken = children.NextPageToken;
                }
                catch (Exception e)
                {
                    Console.WriteLine("An error occurred: " + e.Message);
                    request.PageToken = null;
                }
            } while (!String.IsNullOrEmpty(request.PageToken));

            return(string.Empty);
        }
Exemple #5
0
        public static int NumChildsInFolder(string folderId, DriveService service)
        {
            ChildrenResource.ListRequest request = service.Children.List(folderId);
            request.Fields = "items(id)";
            request.Q      = "mimeType != 'application/vnd.google-apps.folder' and trashed = false";

            int totalChildren = 0;

            do
            {
                try
                {
                    ChildList children = request.Execute();

                    totalChildren += children.Items.Count;

                    request.PageToken = children.NextPageToken;
                }
                catch (Exception e)
                {
                    Console.WriteLine("An error occurred: " + e.Message);
                    request.PageToken = null;
                }
            } while (!String.IsNullOrEmpty(request.PageToken));

            return(totalChildren);
        }
Exemple #6
0
        //Imprime los id de los archivos en la nube
        public static void PrintFilesInFolder(DriveService service, String folderId)
        {
            ChildrenResource.ListRequest request = service.Children.List(folderId);


            do
            {
                try
                {
                    ChildList children = request.Execute();


                    foreach (ChildReference child in children.Items)
                    {
                        string prueba = ("File Id: " + child.Id);
                    }


                    request.PageToken = children.NextPageToken;
                }
                catch (Exception e)
                {
                    Console.WriteLine("An error occurred: " + e.Message);
                    request.PageToken = null;
                }
            } while (!String.IsNullOrEmpty(request.PageToken));

            Console.Read();
        }
        public string  getchildInFolder(DriveService service, String folderId)
        {
            ChildrenResource.ListRequest request = service.Children.List(folderId);
            string file_id = "";

            do
            {
                try
                {
                    ChildList children = request.Execute();

                    foreach (ChildReference child in children.Items)
                    {
                        Google.Apis.Drive.v2.Data.File file1 = service.Files.Get(child.Id).Execute();
                        if (file1.Title.StartsWith("Build Plan"))
                        {
                            ListViewItem item = new ListViewItem(new string[2] {
                                file1.Title, child.Id
                            });
                            //  googleshareDoc = file1.Title;
                            this.spreadsheetListView.Items.Add(item);
                        }
                    }
                    request.PageToken = children.NextPageToken;
                }
                catch (Exception e)
                {
                    Console.WriteLine("An error occurred: " + e.Message);
                    request.PageToken = null;
                }
            } while (!String.IsNullOrEmpty(request.PageToken));

            return(file_id);
        }
Exemple #8
0
        public static List <File> ListFolderContent(DriveService service, string idFolder)
        {
            ChildrenResource.ListRequest request = service.Children.List(idFolder);
            List <File> files = new List <File>();

            request.Q = string.Format("'{0}' in parents", idFolder);

            do
            {
                try
                {
                    ChildList children = request.Execute();

                    foreach (ChildReference child in children.Items)
                    {
                        files.Add(GetFileById(service, child.Id));
                    }

                    request.PageToken = children.NextPageToken;
                }
                catch
                {
                    request.PageToken = null;
                }
            } while (!string.IsNullOrEmpty(request.PageToken));
            return(files);
        }
Exemple #9
0
        public static List <string> AllChildsInFolder(string folderId, DriveService service)
        {
            ChildrenResource.ListRequest request = service.Children.List(folderId);

            List <string> childIds = new List <string>();

            do
            {
                try
                {
                    ChildList children = request.Execute();

                    foreach (ChildReference child in children.Items)
                    {
                        var getRequest = service.Files.Get(child.Id);
                        getRequest.Fields = "mimeType , id, labels";
                        var    childInfo = getRequest.Execute();
                        string mimetype  = childInfo.MimeType;
                        bool   isTrashed = (bool)childInfo.Labels.Trashed;
                        if (mimetype != "application/vnd.google-apps.folder" && !isTrashed)
                        {
                            childIds.Add(child.Id);
                        }
                    }
                    request.PageToken = children.NextPageToken;
                }
                catch (Exception e)
                {
                    Console.WriteLine("An error occurred: " + e.Message);
                    request.PageToken = null;
                }
            } while (!String.IsNullOrEmpty(request.PageToken));

            return(childIds);
        }
Exemple #10
0
        public static IList <File> GetFoldersByIdParentFolder(DriveService service, string idParentFolder)
        {
            IList <File> folders = new List <File>();

            try
            {
                ChildrenResource.ListRequest list = service.Children.List(idParentFolder);

                list.Q = "mimeType = 'application/vnd.google-apps.folder' and trashed=false";

                do
                {
                    try
                    {
                        ChildList children = list.Execute();

                        foreach (ChildReference child in children.Items)
                        {
                            folders.Add(GetFileById(service, child.Id));
                        }
                        list.PageToken = children.NextPageToken;
                    }
                    catch (Exception ex)
                    {
                        throw new Exception(ex.Message);
                    }
                } while (!string.IsNullOrEmpty(list.PageToken));
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }

            return(folders);
        }
Exemple #11
0
        static void DriveDirectory(DriveService service, string folderId, string path)
        {
            ChildrenResource.ListRequest request = service.Children.List(folderId);
            request.MaxResults = 1000;

            File file = null;

            do
            {
                try
                {
                    ChildList children = request.Execute();

                    foreach (ChildReference child in children.Items)
                    {
                        file = service.Files.Get(child.Id).Execute();

                        if (file.MimeType == "application/vnd.google-apps.folder")
                        {
                            dirPath += file.Title + @"\";
                            DriveDirectory(service, file.Id, dirPath);
                            dirPath = dirPath.Substring(0, dirPath.Length - (file.Title.Length + 1));
                        }
                        else
                        {
                            //Console.WriteLine(file.Title);
                            Console.WriteLine(@"{0}{1}", path, file.Title);


                            mysql.Open();
                            command = mysql.CreateCommand();
                            if (numberTable == 1)
                            {
                                command.CommandText = "INSERT INTO games_edit(name, size, hash, fileid, url) VALUES(@name, @size, @hash, @fileid, @url)";
                            }
                            else
                            {
                                command.CommandText = "INSERT INTO mods_edit(name, size, hash, fileid, url) VALUES(@name, @size, @hash, @fileid, @url)";
                            }
                            command.Parameters.AddWithValue("@name", path + file.Title);
                            command.Parameters.AddWithValue("@size", file.FileSize);
                            command.Parameters.AddWithValue("@hash", file.Md5Checksum);
                            command.Parameters.AddWithValue("@fileid", file.Id);
                            command.Parameters.AddWithValue("@url", file.DownloadUrl);
                            command.ExecuteNonQuery();
                            mysql.Close();
                        }
                    }
                    request.PageToken = children.NextPageToken;
                }
                catch (Exception e)
                {
                    Console.WriteLine("ERROR: Doslo je do greske sljedece oznake,\n" + e.Message);
                    request.PageToken = null;
                    Console.ReadKey();
                }
            } while (!String.IsNullOrEmpty(request.PageToken));
        }
        private void copyFolderItems(FileManagerDirectoryContent item, string targetID)
        {
            DriveService service = GetService();

            ChildrenResource.ListRequest request = service.Children.List(item.Id);
            ChildList children = request.Execute();

            foreach (ChildReference child in children.Items)
            {
                var childDetails = service.Files.Get(child.Id).Execute();
                if (childDetails.MimeType == "application/vnd.google-apps.folder")
                {
                    File file = new File()
                    {
                        Title   = childDetails.Title,
                        Parents = new List <ParentReference> {
                            new ParentReference()
                            {
                                Id = targetID
                            }
                        },
                        MimeType = "application/vnd.google-apps.folder"
                    };
                    request.Fields = "id";
                    File SubFolder = (service.Files.Insert(file)).Execute();
                    FileManagerDirectoryContent FileDetail = new FileManagerDirectoryContent();
                    FileDetail.Name         = childDetails.Title;
                    FileDetail.Id           = childDetails.Id;
                    FileDetail.IsFile       = false;
                    FileDetail.Type         = "folder";
                    FileDetail.FilterId     = obtainFilterId(childDetails);
                    FileDetail.HasChild     = getChildrenById(childDetails.Id);
                    FileDetail.DateCreated  = Convert.ToDateTime(childDetails.ModifiedDate);
                    FileDetail.DateModified = Convert.ToDateTime(childDetails.ModifiedDate);
                    copyFolderItems(FileDetail, SubFolder.Id);
                }
                else
                {
                    File SubFile = new File()
                    {
                        Title   = childDetails.Title,
                        Parents = new List <ParentReference> {
                            new ParentReference()
                            {
                                Id = targetID
                            }
                        }
                    };
                    FilesResource.CopyRequest subFilerequest = service.Files.Copy(SubFile, child.Id);
                    subFilerequest.Execute();
                }
            }
        }
Exemple #13
0
        static void DriveDir(DriveService service, string folderId)
        {
            if (service == null)
            {
                Console.WriteLine("Authentication error");
                Console.ReadLine();
            }

            try
            {
                ChildrenResource.ListRequest request1 = service.Children.List(folderId);
                request1.MaxResults = 1000;
                List <File> files = new List <File>();

                do
                {
                    try
                    {
                        ChildList children = request1.Execute();

                        foreach (ChildReference child in children.Items)
                        {
                            File file = service.Files.Get(child.Id).Execute();

                            if (file.MimeType == "application/vnd.google-apps.folder")
                            {
                                Console.WriteLine("DIR:\t{0}", file.Title);
                                DriveDir(service, file.Id);
                            }
                            else
                            {
                                //files.Add(file);
                                Console.WriteLine("FILE:\t{0}", file.Title);
                            }
                        }
                        request1.PageToken = children.NextPageToken;
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine("An error occurred: " + e.Message);
                        request1.PageToken = null;
                    }
                } while (!String.IsNullOrEmpty(request1.PageToken));
            }
            catch (Exception ex)
            {
            }
        }
        public List <Google.Apis.Drive.v2.Data.File> GetRoot()
        {
            List <Google.Apis.Drive.v2.Data.File> result = new List <Google.Apis.Drive.v2.Data.File>();

            ChildrenResource.ListRequest child_req = _driveService.Children.List("root");
            ChildList ch = child_req.Execute();

            foreach (ChildReference a in ch.Items)
            {
                FilesResource.GetRequest       get_file = _driveService.Files.Get(a.Id);
                Google.Apis.Drive.v2.Data.File file_obj = get_file.Execute();
                result.Add(file_obj);
            }

            return(result);
        }
        public FileManagerResponse Move(string path, string targetPath, string[] names, string[] replacedItemNames, FileManagerDirectoryContent TargetData, params FileManagerDirectoryContent[] data)
        {
            FileManagerResponse moveResponse             = new FileManagerResponse();
            DriveService        service                  = GetService();
            List <FileManagerDirectoryContent> moveFiles = new List <FileManagerDirectoryContent>();

            ChildrenResource.ListRequest request = service.Children.List(data[0].Id);
            ChildList     children      = request.Execute();
            List <string> childFileList = children.Items.Select(x => x.Id).ToList();

            if (childFileList.IndexOf(TargetData.Id) != -1)
            {
                ErrorDetails er = new ErrorDetails();
                er.Code            = "400";
                er.Message         = "The destination folder is the subfolder of the source folder.";
                moveResponse.Error = er;
                return(moveResponse);
            }
            foreach (FileManagerDirectoryContent item in data)
            {
                FilesResource.GetRequest fileRequest = service.Files.Get(item.Id);
                fileRequest.Fields = "parents";
                var    file            = fileRequest.Execute();
                string previousParents = String.Join(",", file.Parents.Select(t => t.Id));
                FilesResource.UpdateRequest moveRequest = service.Files.Update(new File(), item.Id);
                moveRequest.Fields        = "id, parents";
                moveRequest.AddParents    = TargetData.Id;
                moveRequest.RemoveParents = previousParents;
                file = moveRequest.Execute();
                File filedetails = service.Files.Get(file.Id).Execute();
                FileManagerDirectoryContent FileDetail = new FileManagerDirectoryContent();
                FileDetail.Name         = filedetails.Title;
                FileDetail.Id           = filedetails.Id;
                FileDetail.IsFile       = filedetails.MimeType == "application/vnd.google-apps.folder" ? false : true;
                FileDetail.Type         = filedetails.FileExtension == null ? "folder" : filedetails.FileExtension;
                FileDetail.HasChild     = getChildrenById(filedetails.Id);
                FileDetail.Size         = item.Size;
                FileDetail.FilterPath   = targetPath.Replace("/", @"\");
                FileDetail.FilterId     = obtainFilterId(filedetails);
                FileDetail.DateCreated  = Convert.ToDateTime(filedetails.ModifiedDate);
                FileDetail.DateModified = Convert.ToDateTime(filedetails.ModifiedDate);
                moveFiles.Add(FileDetail);
            }
            moveResponse.Files = moveFiles;
            return(moveResponse);
        }
Exemple #16
0
        public static List <GoogleDriveFiles> GetContainsInFolderCustom(String folderId)
        {
            List <string> ChildList = new List <string>();

            Google.Apis.Drive.v2.DriveService ServiceV2          = GetService_v2();
            ChildrenResource.ListRequest      ChildrenIDsRequest = ServiceV2.Children.List(folderId);

            // for getting only folders
            ChildrenIDsRequest.Q      = "mimeType!='application/vnd.google-apps.folder'"; //file catched by usiing ! sign
            ChildrenIDsRequest.Fields = "files(id,name)";
            do
            {
                var children = ChildrenIDsRequest.Execute();

                if (children.Items != null && children.Items.Count > 0)
                {
                    foreach (var file in children.Items)
                    {
                        ChildList.Add(file.Id);
                    }
                }
                ChildrenIDsRequest.PageToken = children.NextPageToken;
            } while (!String.IsNullOrEmpty(ChildrenIDsRequest.PageToken));

            //Get All File List
            //  List<GoogleDriveFiles> AllFileList = GetDriveFiles();
            List <GoogleDriveFiles> Filter_FileList = new List <GoogleDriveFiles>();


            foreach (string Id in ChildList)
            {
                GoogleDriveFiles File = new GoogleDriveFiles
                {
                    Id          = Id,
                    Name        = "",
                    Size        = 0,
                    Version     = 0,
                    CreatedTime = null
                };
                Filter_FileList.Add(File);
            }
            return(Filter_FileList);
        }
Exemple #17
0
        public IDictionary <String, String> GetChildElements(String rootID)
        {
            ChildrenResource.ListRequest request = service.Children.List(rootID);
            IDictionary <String, String> result  = new Dictionary <String, String>();
            ChildList list = request.Execute();

            foreach (ChildReference child in list.Items)
            {
                foreach (File file in all)
                {
                    if (child.Id.Equals(file.Id))
                    {
                        result.Add(file.Id, file.Title);
                    }
                }
            }

            return(result);
        }
        public List <Google.Apis.Drive.v2.Data.File> GetChildren(string dir_name)
        {
            List <Google.Apis.Drive.v2.Data.File> result = new List <Google.Apis.Drive.v2.Data.File>();

            FilesResource.ListRequest req = _driveService.Files.List();
            req.Q = "title='" + dir_name + "'";
            FileList children_list = req.Execute();

            ChildrenResource.ListRequest child_req = _driveService.Children.List(children_list.Items[0].Id);
            ChildList ch = child_req.Execute();

            foreach (ChildReference a in ch.Items)
            {
                FilesResource.GetRequest       get_file = _driveService.Files.Get(a.Id);
                Google.Apis.Drive.v2.Data.File file_obj = get_file.Execute();
                result.Add(file_obj);
            }

            return(result);
        }
        // Calculates the folder size value
        private void getFolderSize(string folderdId)
        {
            DriveService service = GetService();

            ChildrenResource.ListRequest request = service.Children.List(folderdId);
            ChildList children = request.Execute();
            List <Google.Apis.Drive.v2.Data.ChildReference> childFileList = children.Items.ToList();

            foreach (var child in childFileList)
            {
                if (service.Files.Get(children.Items[0].Id).Execute().MimeType == "application/vnd.google-apps.folder")
                {
                    getFolderSize(child.Id);
                }
                else
                {
                    sizeValue = sizeValue + long.Parse(service.Files.Get(children.Items[0].Id).Execute().FileSize.ToString());
                }
            }
        }
        // Download files within the folder
        private void DownloadFolderFiles(string Id, string Name, ZipArchive archive, ZipArchiveEntry zipEntry)
        {
            DriveService  service = GetService();
            DirectoryInfo info    = new DirectoryInfo(Path.GetTempPath() + Name);

            ChildrenResource.ListRequest request = service.Children.List(Id);
            ChildList children = request.Execute();
            List <Google.Apis.Drive.v2.Data.ChildReference> childFileList = children.Items.ToList();

            foreach (ChildReference child in childFileList)
            {
                if (service.Files.Get(child.Id).Execute().MimeType == "application/vnd.google-apps.folder")
                {
                    info.CreateSubdirectory(service.Files.Get(child.Id).Execute().Title);
                    zipEntry = archive.CreateEntry(Name + "\\" + service.Files.Get(child.Id).Execute().Title + "/");
                    DownloadFolderFiles(child.Id, Name + "\\" + service.Files.Get(child.Id).Execute().Title, archive, zipEntry);
                }
                else
                {
                    Stream file;
                    File   fileProperties = service.Files.Get(child.Id).Execute();
                    if (System.IO.File.Exists(Path.Combine(Path.GetTempPath() + Name, fileProperties.Title)))
                    {
                        System.IO.File.Delete(Path.Combine(Path.GetTempPath() + Name, fileProperties.Title));
                    }
                    byte[] subFileContent = service.HttpClient.GetByteArrayAsync(fileProperties.DownloadUrl).Result;
                    using (file = System.IO.File.OpenWrite(Path.Combine(Path.GetTempPath() + Name, fileProperties.Title)))
                    {
                        file.Write(subFileContent, 0, subFileContent.Length);
                        file.Close();
                        zipEntry = archive.CreateEntryFromFile(Path.Combine(Path.GetTempPath() + Name, fileProperties.Title), Name + "\\" + fileProperties.Title, CompressionLevel.Fastest);
                    }
                }
            }
            if (System.IO.File.Exists(Path.Combine(Path.GetTempPath(), Name)))
            {
                System.IO.File.Delete(Path.Combine(Path.GetTempPath(), Name));
            }
        }
Exemple #21
0
        private void GetFolderItems(ref List <Item> lstItems, string rootid)
        {
            //ChildList listadoFiles = service.Children.List(rootid).Execute();
            //Q = "mimeType='application/vnd.google-apps.folder'

            ChildrenResource.ListRequest request = service.Children.List(rootid);
            request.Q = "mimeType != 'application/vnd.google-apps.folder'";
            ChildList listadoFiles = request.Execute();


            if (listadoFiles != null && listadoFiles.Items.Count > 0)
            {
                foreach (ChildReference fold in listadoFiles.Items)
                {
                    Item itm = new Item();
                    itm.GoogleID       = fold.Id;
                    itm.GoogleParentID = rootid;
                    itm.IsFolder       = false;
                    lstItems.Add(itm);
                }
            }
        }
        // Reads the file(s) and folder(s)
        public FileManagerResponse GetFiles(string path, bool showHiddenItems, params FileManagerDirectoryContent[] data)
        {
            string id = (path == "/") ? null : data[0].Id;
            // Create Drive API service.
            DriveService service = GetService();

            // Define parameters of request.
            FilesResource.ListRequest listRequest = service.Files.List();
            listRequest.Fields = "nextPageToken, files(*)";
            List <Google.Apis.Drive.v2.Data.File> result = new List <Google.Apis.Drive.v2.Data.File>();

            FilesResource.ListRequest req = service.Files.List();
            IList <Google.Apis.Drive.v2.Data.File> files = req.Execute().Items;
            FileManagerResponse readResponse             = new FileManagerResponse();

            if (files != null && files.Count > 0)
            {
                FileManagerDirectoryContent    cwd       = new FileManagerDirectoryContent();
                Google.Apis.Drive.v2.Data.File directory = (id == null) ? service.Files.Get(files.Where(a => a.Parents.Any(c => (bool)c.IsRoot == true)).ToList()[0].Parents[0].Id).Execute() :
                                                           service.Files.Get(id).Execute();
                cwd.Name = directory.Title;
                cwd.Size = directory.FileSize != null?long.Parse(directory.FileSize.ToString()) : 0;

                cwd.IsFile       = directory.MimeType == "application/vnd.google-apps.folder" ? false : true;
                cwd.DateModified = Convert.ToDateTime(directory.ModifiedDate);
                cwd.DateCreated  = Convert.ToDateTime(directory.CreatedDate);
                cwd.Id           = directory.Id;
                cwd.HasChild     = true;
                cwd.Type         = "Folder";
                this.path        = new List <string>();
                cwd.FilterPath   = directory.Parents.Count == 0 ? "" : data[0].FilterPath;
                List <FileManagerDirectoryContent> rootFileList = files.Where(x => x.Parents.Any(c => (bool)c.IsRoot == true)).Select(x => new FileManagerDirectoryContent()
                {
                    Id           = x.Id,
                    Name         = x.Title,
                    Size         = x.FileSize != null ? long.Parse(x.FileSize.ToString()) : 0,
                    DateCreated  = Convert.ToDateTime(x.CreatedDate),
                    DateModified = Convert.ToDateTime(x.ModifiedDate),
                    Type         = x.FileExtension == null ? "folder" : x.FileExtension,
                    HasChild     = getChildrenById(x.Id),
                    FilterPath   = @"\",
                    FilterId     = obtainFilterId(x),
                    IsFile       = x.MimeType == "application/vnd.google-apps.folder" ? false : true
                }).ToList();
                if (id == null)
                {
                    readResponse.Files = rootFileList;
                }
                else
                {
                    ChildrenResource.ListRequest request = service.Children.List(id);
                    ChildList children = request.Execute();
                    List <FileManagerDirectoryContent> childFileList = new List <FileManagerDirectoryContent>();
                    string[] childId = children.Items.Select(x => x.Id).ToList().ToArray();
                    foreach (string idValue in childId)
                    {
                        File details = service.Files.Get(idValue).Execute();
                        FileManagerDirectoryContent content = new FileManagerDirectoryContent()
                        {
                            Id   = idValue,
                            Name = details.Title,
                            Size = details.FileSize != null?long.Parse(details.FileSize.ToString()) : 0,
                                       DateCreated  = Convert.ToDateTime(details.CreatedDate),
                                       DateModified = Convert.ToDateTime(details.ModifiedDate),
                                       Type         = details.FileExtension,
                                       FilterPath   = data.Length != 0 ? obtainFilterPath(details, true) + @"\" : @"\",
                                       FilterId     = obtainFilterId(details),
                                       HasChild     = getChildrenById(idValue),
                                       IsFile       = details.MimeType == "application/vnd.google-apps.folder" ? false : true
                        };
                        childFileList.Add(content);
                    }
                    readResponse.Files = childFileList;
                }
                readResponse.CWD = cwd;
                return(readResponse);
            }
            return(readResponse);
        }
Exemple #23
0
        static void Main(string[] args)
        {
            //Google Drive scopes Documentation:   https://developers.google.com/drive/web/scopes
            string[] scopes = new string[] { DriveService.Scope.Drive,                 // view and manage your files and documents
                                             DriveService.Scope.DriveAppdata,          // view and manage its own configuration data
                                             DriveService.Scope.DriveAppsReadonly,     // view your drive apps
                                             DriveService.Scope.DriveFile,             // view and manage files created by this app
                                             DriveService.Scope.DriveMetadataReadonly, // view metadata for files
                                             DriveService.Scope.DriveReadonly,         // view files and documents on your drive
                                             DriveService.Scope.DriveScripts };        // modify your app scripts

            DriveService service = GDriveAccount.Authenticate("*****@*****.**", "Columbia State-99db1bd2a00e.json", scopes);

            if (service == null)
            {
                Console.WriteLine("Authentication error");
                Console.ReadLine();
            }

            DriveDir(service, "0Byi5ne7d961QVS1XOGlPaTRKc28");

            try
            {
                ChildrenResource.ListRequest request1 = service.Children.List("0Byi5ne7d961QVS1XOGlPaTRKc28");
                int j = 1;
                request1.MaxResults = 1000;
                List <string> folders = new List <string>();
                List <string> files   = new List <string>();
                do
                {
                    try
                    {
                        ChildList children = request1.Execute();

                        foreach (ChildReference child in children.Items)
                        {
                            //Console.WriteLine("{0} File Id: {1}", j, child.Id);
                            File file = service.Files.Get(child.Id).Execute();
                            if (file.MimeType == "application/vnd.google-apps.folder")
                            {
                                folders.Add(file.Title);
                            }
                            else
                            {
                                files.Add(file.Title);
                            }

                            //Console.WriteLine("Title: {0} - MIME type: {1}", file.Title, file.MimeType);
                            //Console.WriteLine();
                            //j++;
                        }
                        request1.PageToken = children.NextPageToken;
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine("An error occurred: " + e.Message);
                        request1.PageToken = null;
                    }
                } while (!String.IsNullOrEmpty(request1.PageToken));

                foreach (string dir in  folders)
                {
                    Console.WriteLine(dir);
                }

                // Listing files with search.
                // This searches for a directory with the name DiamtoSample
                string Q = "title = 'Files' and mimeType = 'application/vnd.google-apps.folder'";
                //string Q = "mimeType = 'application/vnd.google-apps.folder'";
                IList <File> _Files = GoogleDrive.GetFiles(service, null);

                foreach (File item in _Files)
                {
                    Console.WriteLine(item.Title + " " + item.MimeType);
                }

                // If there isn't a directory with this name lets create one.
                if (_Files.Count == 0)
                {
                    _Files.Add(GoogleDrive.createDirectory(service, "Files1", "Files1", "root"));
                }

                // We should have a directory now because we either had it to begin with or we just created one.
                if (_Files.Count != 0)
                {
                    // This is the ID of the directory
                    string directoryId = _Files[0].Id;

                    //Upload a file
                    //File newFile = DaimtoGoogleDriveHelper.uploadFile(service, @"c:\GoogleDevelop\dummyUploadFile.txt", directoryId);
                    File newFile = GoogleDrive.uploadFile(service, @"c:\Games\gtasamp.md5", directoryId);
                    // Update The file
                    //File UpdatedFile = DaimtoGoogleDriveHelper.updateFile(service, @"c:\GoogleDevelop\dummyUploadFile.txt", directoryId, newFile.Id);
                    File UpdatedFile = GoogleDrive.updateFile(service, @"c:\Games\gtasamp.md5", directoryId, newFile.Id);
                    // Download the file
                    GoogleDrive.downloadFile(service, newFile, @"C:\Games\download.txt");
                    // delete The file
                    FilesResource.DeleteRequest request = service.Files.Delete(newFile.Id);
                    request.Execute();
                }

                // Getting a list of ALL a users Files (This could take a while.)
                _Files = GoogleDrive.GetFiles(service, null);

                foreach (File item in _Files)
                {
                    Console.WriteLine(item.Title + " " + item.MimeType);
                }
            }
            catch (Exception ex)
            {
                int i = 1;
            }

            Console.ReadLine();
        }
Exemple #24
0
        /// <summary>
        /// List all of the files and directories for the current user.
        ///
        /// Documentation: https://developers.google.com/drive/v2/reference/files/list
        /// Documentation Search: https://developers.google.com/drive/web/search-parameters
        /// </summary>
        /// <param name="service">a Valid authenticated DriveService</param>
        /// <param name="search">if Search is null will return all files</param>
        /// <returns></returns>
        public static List <File> GetFiles(DriveService service, string folderId)
        {
            List <File> Files = new List <File>();

            try
            {
                ChildrenResource.ListRequest request = service.Children.List(folderId);
                request.MaxResults = 1000;

                do
                {
                    try
                    {
                        ChildList children = request.Execute();

                        foreach (ChildReference child in children.Items)
                        {
                            File file = service.Files.Get(child.Id).Execute();

                            Console.WriteLine("Title: " + file.Title);

                            Console.WriteLine("MIME type: " + file.MimeType);
                            Console.WriteLine();
                        }
                        request.PageToken = children.NextPageToken;
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine("An error occurred: " + e.Message);
                        request.PageToken = null;
                    }
                } while (!String.IsNullOrEmpty(request.PageToken));

                //List all of the files and directories for the current user.
                // Documentation: https://developers.google.com/drive/v2/reference/files/list
                FilesResource.ListRequest list = service.Files.List();
                list.MaxResults = 1000;
                //if (search != null)
                //{
                //    list.Q = search;
                //}
                FileList filesFeed = list.Execute();

                //// Loop through until we arrive at an empty page
                while (filesFeed.Items != null)
                {
                    // Adding each item  to the list.
                    foreach (File item in filesFeed.Items)
                    {
                        Files.Add(item);
                    }

                    // We will know we are on the last page when the next page token is
                    // null.
                    // If this is the case, break.
                    if (filesFeed.NextPageToken == null)
                    {
                        break;
                    }

                    // Prepare the next page of results
                    list.PageToken = filesFeed.NextPageToken;

                    // Execute and process the next page request
                    filesFeed = list.Execute();
                }
            }
            catch (Exception ex)
            {
                // In the event there is an error with the request.
                Console.WriteLine(ex.Message);
            }
            return(Files);
        }
        public FileManagerResponse Copy(string path, string targetPath, string[] names, string[] replacedItemNames, FileManagerDirectoryContent TargetData, params FileManagerDirectoryContent[] data)
        {
            FileManagerResponse copyResponse             = new FileManagerResponse();
            DriveService        service                  = GetService();
            List <FileManagerDirectoryContent> copyFiles = new List <FileManagerDirectoryContent>();

            ChildrenResource.ListRequest childRequest = service.Children.List(data[0].Id);
            ChildList     children      = childRequest.Execute();
            List <string> childFileList = children.Items.Select(x => x.Id).ToList();

            if (childFileList.IndexOf(TargetData.Id) != -1)
            {
                ErrorDetails er = new ErrorDetails();
                er.Code            = "400";
                er.Message         = "The destination folder is the subfolder of the source folder.";
                copyResponse.Error = er;
                return(copyResponse);
            }
            foreach (FileManagerDirectoryContent item in data)
            {
                File copyFile;
                try
                {
                    File file = new File()
                    {
                        Title   = item.Name,
                        Parents = new List <ParentReference> {
                            new ParentReference()
                            {
                                Id = TargetData.Id
                            }
                        }
                    };
                    if (item.IsFile)
                    {
                        // Copy the file
                        FilesResource.CopyRequest request = service.Files.Copy(file, item.Id);
                        copyFile = request.Execute();
                    }
                    else
                    {
                        file.MimeType = "application/vnd.google-apps.folder";
                        FilesResource.InsertRequest request = service.Files.Insert(file);
                        request.Fields = "id";
                        copyFile       = request.Execute();
                        copyFolderItems(item, copyFile.Id);
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine("An error occurred: " + e.Message);
                    return(null);
                }
                File filedetails = service.Files.Get(copyFile.Id).Execute();
                FileManagerDirectoryContent FileDetail = new FileManagerDirectoryContent();
                FileDetail.Name         = filedetails.Title;
                FileDetail.Id           = filedetails.Id;
                FileDetail.IsFile       = filedetails.MimeType == "application/vnd.google-apps.folder" ? false : true;
                FileDetail.Type         = filedetails.FileExtension == null ? "folder" : filedetails.FileExtension;
                FileDetail.HasChild     = getChildrenById(filedetails.Id);
                FileDetail.FilterId     = obtainFilterId(filedetails);
                FileDetail.Size         = item.Size;
                FileDetail.FilterPath   = targetPath.Replace("/", @"\");
                FileDetail.DateCreated  = Convert.ToDateTime(filedetails.ModifiedDate);
                FileDetail.DateModified = Convert.ToDateTime(filedetails.ModifiedDate);
                copyFiles.Add(FileDetail);
            }
            copyResponse.Files = copyFiles;
            return(copyResponse);
        }