コード例 #1
0
        internal static File CreateDirectory(DriveService service, string title, string parent, params Property[] properties)
        {
            File NewDirectory = null;

            // Create metaData for a new Directory
            File body = new File();

            body.Title    = title;
            body.MimeType = "application/vnd.google-apps.folder";
            body.Parents  = new List <ParentReference>()
            {
                new ParentReference()
                {
                    Id = parent
                }
            };

            body.Properties = new List <Property>();
            foreach (var property in properties)
            {
                body.Properties.Add(property);
            }

            FilesResource.InsertRequest request = service.Files.Insert(body);
            NewDirectory = request.Execute();


            return(NewDirectory);
        }
コード例 #2
0
ファイル: GoogleDriveService.cs プロジェクト: fanslations/web
        //// <summary>
        /// Create a new Directory.
        /// Documentation: https://developers.google.com/drive/v2/reference/files/insert
        /// </summary>
        /// <param name="_service">a Valid authenticated DriveService</param>
        /// <param name="_title">The title of the file. Used to identify file or folder name.</param>
        /// <param name="_description">A short description of the file.</param>
        /// <param name="_parent">Collection of parent folders which contain this file.
        ///                       Setting this field will put the file in all of the provided folders. root folder.</param>
        /// <returns></returns>
        public static File createDirectory(DriveService _service, string _title, string _description, string _parent)
        {
            File NewDirectory = null;

            // Create metaData for a new Directory
            File body = new File();

            body.Title       = _title;
            body.Description = _description;
            body.MimeType    = "application/vnd.google-apps.folder";
            body.Parents     = new List <ParentReference>()
            {
                new ParentReference()
                {
                    Id = _parent
                }
            };
            try
            {
                FilesResource.InsertRequest request = _service.Files.Insert(body);
                NewDirectory = request.Execute();
            }
            catch (Exception e)
            {
                Console.WriteLine("An error occurred: " + e.Message);
            }

            return(NewDirectory);
        }
コード例 #3
0
        private static File CreateGoogleSheet(ModelInfo modelInfo, string projectFolderId)
        {
            File sheetFile = null;

            try
            {
                if (null == service)
                {
                    service = GetUserCredential();
                }

                if (null != service)
                {
                    File body = new File();
                    body.Title       = modelInfo.DocTitle;
                    body.Description = "Created by Project Replicator";
                    body.Parents     = new List <ParentReference>()
                    {
                        new ParentReference()
                        {
                            Id = projectFolderId
                        }
                    };
                    body.MimeType = "application/vnd.google-apps.spreadsheet";

                    FilesResource.InsertRequest request = service.Files.Insert(body);
                    sheetFile = request.Execute();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Failed to create google sheet.\n" + ex.Message, "Create Google Sheet", MessageBoxButton.OK, MessageBoxImage.Warning);
            }
            return(sheetFile);
        }
コード例 #4
0
        public static Google.Apis.Drive.v2.Data.File createDirectory(DriveService _service, string _title, string _description, string _parent)
        {
            Google.Apis.Drive.v2.Data.File NewDirectory = null;

            // Create metaData for a new Directory
            Google.Apis.Drive.v2.Data.File body = new Google.Apis.Drive.v2.Data.File();
            body.Title       = _title;
            body.Description = _description;
            body.MimeType    = "application/vnd.google-apps.folder";
            body.Parents     = new List <ParentReference>()
            {
                new ParentReference()
                {
                    Id = _parent
                }
            };

            try
            {
                if (!_service.Files.Equals("_title"))
                {
                    FilesResource.InsertRequest request = _service.Files.Insert(body);
                    NewDirectory = request.Execute();
                }
            }
            catch //(Exception e)
            {
                //Form1.AppendOutputText("ERROR (createDirectory): " + e.Message, Color.Red);
            }

            return(NewDirectory);
        }
コード例 #5
0
        public static Google.Apis.Drive.v2.Data.File createDirectory(DriveService _service, string _title, string _description, string _parent)
        {
            Google.Apis.Drive.v2.Data.File NewDirectory = null;
            Google.Apis.Drive.v2.Data.File body         = new Google.Apis.Drive.v2.Data.File
            {
                Title       = _title,
                Description = _description,
                MimeType    = "application/vnd.google-apps.folder",
                Parents     = new List <ParentReference>()
                {
                    new ParentReference()
                    {
                        Id = _parent
                    }
                }
            };

            try
            {
                GException = null;
                FilesResource.InsertRequest request = _service.Files.Insert(body);
                NewDirectory = request.Execute();
            }
            catch (Exception ex) { GException = ex; }

            return(NewDirectory);
        }
コード例 #6
0
        public File CrearCarpeta(string _title, string _description, string _parent)
        {
            File carpeta = null;

            File body = new File();

            body.Title       = _title;
            body.Description = _description;
            body.MimeType    = "application/vnd.google-apps.folder";
            body.Parents     = new List <ParentReference>()
            {
                new ParentReference()
                {
                    Id = _parent
                }
            };
            try
            {
                FilesResource.InsertRequest request = service.Files.Insert(body);
                carpeta = request.Execute();
            }
            catch (Exception e)
            {
                Console.WriteLine("An error occurred: " + e.Message);
            }

            return(carpeta);
        }
コード例 #7
0
        public Google.Apis.Drive.v2.Data.File UploadFolder(Google.Apis.Drive.v2.Data.File folder)
        {
            if (!serviceStarted)
            {
                return(null);
            }

            FilesResource.InsertRequest    request = driverservice.Files.Insert(folder);
            Google.Apis.Drive.v2.Data.File file    = request.Execute();
            return(file);
        }
コード例 #8
0
ファイル: Drive.cs プロジェクト: albertcrowley/scrumnotes
        /// <summary>
        /// Creates a scrum notes folder
        ///
        /// </summary>
        /// <returns>Drive File pointing to the scrum notes folder</returns>

        public File createScrumNotesFolder()
        {
            Google.Apis.Drive.v2.Data.File body = new Google.Apis.Drive.v2.Data.File();
            body.Title       = ScrumNotesFolderName;
            body.Description = ScrumNotesFolderName;
            body.MimeType    = "application/vnd.google-apps.folder";

            FilesResource.InsertRequest insReq = service.Files.Insert(body);

            return(insReq.Execute()); // TODO: this doesn't return the newly created folder....not sure why
        }
コード例 #9
0
    public void CreateDirectory(string title, string dirPath)
    {
        string parentID;

        if (dirPath != null)
        {
            var Directory = GetFileByPath(dirPath);
            if (Directory != null)
            {
                if (Directory.MimeType.Equals("application/vnd.google-apps.folder"))
                {
                    parentID = Directory.Id;
                }
                else
                {
                    throw new Exception("Given path is not a directory");
                }
            }
            else
            {
                throw new Exception("No directory found at given path");
            }
        }
        else
        {
            parentID = service.About.Get().Execute().RootFolderId;
        }

        Google.Apis.Drive.v2.Data.File body = new Google.Apis.Drive.v2.Data.File();
        body.Title       = title;
        body.Description = "Descripiton";
        body.MimeType    = "application/vnd.google-apps.folder";
        body.Parents     = new List <ParentReference>()
        {
            new ParentReference()
            {
                Id = parentID
            }
        };
        try
        {
            FilesResource.InsertRequest request = service.Files.Insert(body);
            request.Execute();
        }
        catch (Exception e)
        {
            throw new Exception("An error occurred: " + e.Message);
        }
    }
コード例 #10
0
        public static Google.Apis.Drive.v2.Data.File createDirectory(DriveService _service, string _title, string _description, string _id)
        {
            if (!CheckInternetConnection())
            {
                return(null);
            }
            Google.Apis.Drive.v2.Data.File NewDirectory = null;

            // Create metaData for a new Directory
            var body = new Google.Apis.Drive.v2.Data.File();

            body.Title       = _title;
            body.Description = _description;
            body.MimeType    = "application/vnd.google-apps.folder";

            // TODO: Remove this

            /*
             * body.UserPermission = new Permission
             * {
             *  Type = "anyone",
             *  Role = "reader",
             *  WithLink = true
             * };
             */

            try
            {
                if (_id != null)
                {
                    FilesResource.UpdateRequest request = _service.Files.Update(body, _id);
                    NewDirectory = request.Execute();
                }
                else
                {
                    FilesResource.InsertRequest request = _service.Files.Insert(body);
                    NewDirectory = request.Execute();
                }
            }
            catch (Exception e)
            {
                new MaterialDialog("An unexpected error occured", "It looks like something went wrong. If you have an idea, email me at [email protected] or open an issue over at Github!\n\n\n" + e.Message, 500).ShowDialog();
                return(null);
            }

            insertPermission(_service, NewDirectory.Id);
            return(NewDirectory);
        }
コード例 #11
0
 public Google.Apis.Drive.v2.Data.File AddFolder(string name, string parent)
 {
     Google.Apis.Drive.v2.Data.File insertFolder = new Google.Apis.Drive.v2.Data.File();
     insertFolder.Title       = name;
     insertFolder.Description = name;
     insertFolder.MimeType    = "application/vnd.google-apps.folder";
     if (null != parent)
     {
         insertFolder.Parents = new List <ParentReference> {
             new ParentReference()
             {
                 Id = parent
             }
         };
     }
     FilesResource.InsertRequest request = GoogleService.GetInstance().Service(this.m_User).Files.Insert(insertFolder);
     return(request.Execute());
 }
コード例 #12
0
        //private string GetDirectoryId(string title)
        //{
        //    IDictionary<String, String> dirs = GetDirectories();
        //    string result = string.Empty;
        //    //todo linq

        //    foreach (KeyValuePair<String, String> keys in dirs)
        //        if (keys.Value.Equals(title))
        //            return keys.Key;

        //    return result;
        //}

        private string UploadEmptyDirectory(string _title, string _description, string _parent)
        {
            File NewDirectory = null;

            // Create metaData for a new Directory
            File body = new File();

            body.Title       = _title;
            body.Description = _description;
            body.MimeType    = DIRECTORY_MIME_TYPE;
            body.Parents     = new List <ParentReference>()
            {
                new ParentReference()
                {
                    Id = _parent
                }
            };

            FilesResource.InsertRequest request = service.Files.Insert(body);
            NewDirectory = request.Execute();
            return(NewDirectory.Id);
        }
コード例 #13
0
        public static File CreateDirectory(DriveService service, string title, string description, string parent)
        {
            File newsDirectory = null;
            File body          = new File
            {
                Title       = title,
                Description = description,
                MimeType    = DefaultDirectoryMime
            };

            try
            {
                FilesResource.InsertRequest request = service.Files.Insert(body);
                newsDirectory = request.Execute();
            }
            catch (Exception e)
            {
                Console.WriteLine("Error: {0}", e.Message);
            }

            return(newsDirectory);
        }
        // Creates a newFolder
        public virtual FileManagerResponse Create(string path, string name, params FileManagerDirectoryContent[] data)
        {
            DriveService service = GetService();

            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();
            FileManagerResponse         createResponse   = new FileManagerResponse();
            FileManagerDirectoryContent CreateData       = new FileManagerDirectoryContent();
            var fileMetaData = new File()
            {
                Title    = name,
                MimeType = "application/vnd.google-apps.folder",
                Parents  = new List <ParentReference> {
                    new ParentReference()
                    {
                        Id = data[0].Id
                    }
                }
            };

            FilesResource.InsertRequest request = service.Files.Insert(fileMetaData);
            request.Fields          = "id";
            CreateData.Name         = name;
            CreateData.Id           = request.Execute().Id;
            CreateData.IsFile       = false;
            CreateData.Size         = 0;
            CreateData.DateModified = new DateTime();
            CreateData.DateCreated  = new DateTime();
            CreateData.HasChild     = false;
            CreateData.Type         = "folder";
            createResponse.Files    = new FileManagerDirectoryContent[] { CreateData };
            return(createResponse);
        }
コード例 #15
0
ファイル: GoogleDriveHelper.cs プロジェクト: rajeshwarn/blog
        /// <summary>
        /// Create a new Directory.
        /// Documentation: https://developers.google.com/drive/v2/reference/files/insert
        /// </summary>
        /// <param name="service">a Valid authenticated DriveService</param>
        /// <param name="title">The title of the file. Used to identify file or folder name.</param>
        /// <param name="description">A short description of the file.</param>
        /// <param name="idParentFolder">Collection of parent folders which contain this file.
        ///                       Setting this field will put the file in all of the provided folders. root folder.</param>
        /// <returns></returns>
        public static File CreateFolder(DriveService service, string title, string description, string idParentFolder)
        {
            File newDirectory = null;

            // Create metaData for a new Directory
            File body = new File
            {
                Title       = title,
                Description = description,
                MimeType    = "application/vnd.google-apps.folder",
                Parents     = new List <ParentReference> {
                    new ParentReference {
                        Id = idParentFolder
                    }
                }
            };

            try
            {
                FilesResource.InsertRequest request = service.Files.Insert(body);
                newDirectory = request.Execute();

                Permission permission = new Permission
                {
                    Value = "",
                    Type  = "anyone",
                    Role  = "reader"
                };

                service.Permissions.Insert(permission, newDirectory.Id).Execute();
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }

            return(newDirectory);
        }
コード例 #16
0
        private static File GetProjectFolder(ModelInfo modelInfo)
        {
            File projectFolder = null;

            try
            {
                FilesResource.ListRequest request = service.Files.List();
                request.Q = "title = \'Project Replication\'";
                FileList files = request.Execute();

                if (files.Items.Count > 0)
                {
                    string projectReplicationFolderId = files.Items.First().Id;

                    if (modelInfo.HOKStandard)
                    {
                        request   = service.Files.List();
                        request.Q = "title = \'HOK Offices\' and \'" + projectReplicationFolderId + "\' in parents";
                        files     = request.Execute();

                        if (files.Items.Count > 0)
                        {
                            string hokFolderId = files.Items.First().Id;
                            string location    = (!string.IsNullOrEmpty(modelInfo.FileLocation)) ? modelInfo.FileLocation : modelInfo.UserLocation;

                            request   = service.Files.List();
                            request.Q = "title = \'" + location + "\' and \'" + hokFolderId + "\' in parents";
                            files     = request.Execute();

                            if (files.Items.Count > 0)
                            {
                                string locationFolderId  = files.Items.First().Id;
                                string projectFolderName = modelInfo.ProjectNumber + " " + modelInfo.ProjectName;

                                request   = service.Files.List();
                                request.Q = "title = \'" + projectFolderName + "\' and \'" + locationFolderId + "\' in parents";
                                files     = request.Execute();

                                if (files.Items.Count > 0)
                                {
                                    projectFolder = files.Items.First();
                                }
                                else
                                {
                                    //create project folder
                                    File body = new File();
                                    body.Title       = projectFolderName;
                                    body.Description = "Project Number: " + modelInfo.ProjectNumber + ", Project Name: " + modelInfo.ProjectName;
                                    body.MimeType    = "application/vnd.google-apps.folder";
                                    body.Parents     = new List <ParentReference>()
                                    {
                                        new ParentReference()
                                        {
                                            Id = locationFolderId
                                        }
                                    };

                                    FilesResource.InsertRequest insertRequest = service.Files.Insert(body);
                                    projectFolder = insertRequest.Execute();
                                }
                            }
                        }
                    }
                    else
                    {
                        //External Users
                        request   = service.Files.List();
                        request.Q = "title = \'External Users\' and \'" + projectReplicationFolderId + "\' in parents";
                        files     = request.Execute();

                        if (files.Items.Count > 0)
                        {
                            string externalFolderId = files.Items.First().Id;
                            string companyName      = modelInfo.CompanyName;

                            request   = service.Files.List();
                            request.Q = "title = \'" + companyName + "\' and \'" + externalFolderId + "\' in parents";
                            files     = request.Execute();

                            if (files.Items.Count > 0)
                            {
                                projectFolder = files.Items.First();
                            }
                            else
                            {
                                request   = service.Files.List();
                                request.Q = "title = \'Unknown\' and \'" + externalFolderId + "\' in parents";
                                files     = request.Execute();

                                if (files.Items.Count > 0)
                                {
                                    projectFolder = files.Items.First();
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Failed to get project folder.\n" + ex.Message, "Find Project Folder", MessageBoxButton.OK, MessageBoxImage.Warning);
            }
            return(projectFolder);
        }
コード例 #17
0
            protected override void Start()
            {
                try
                {
                    if (Status != StatusType.Queued)
                    {
                        throw new Exception("Stream has not been queued.");
                    }

                    base.Start();

                    List <File> children = null;

                    File parent = API.DriveService._GetCachedFile(_parentId, true, false, ref children);

                    string fileName       = System.IO.Path.GetFileNameWithoutExtension(_originalTitle);
                    string fileExtenstion = System.IO.Path.GetExtension(_originalTitle);

                    string title = fileName;

                    if (!String.IsNullOrEmpty(fileExtenstion))
                    {
                        title += fileExtenstion;
                    }

                    int index = 0;

                    while (true)
                    {
                        bool found = false;

                        foreach (File child in children)
                        {
                            if (child.Title == title)
                            {
                                FileInfoType fileInfoType = API.DriveService.GetFileInfoType(child);

                                if (IsFolder && fileInfoType == FileInfoType.Folder)
                                {
                                    found = true;
                                }
                                else if (!IsFolder && fileInfoType != FileInfoType.Folder)
                                {
                                    found = true;
                                }
                            }
                        }

                        if (!found)
                        {
                            break;
                        }

                        index++;

                        title = fileName + " (" + index + ")";

                        if (!String.IsNullOrEmpty(fileExtenstion))
                        {
                            title += fileExtenstion;
                        }
                    }

                    _title = title;

                    var file = new File();

                    var parentReference = new ParentReference {
                        Id = _parentId
                    };

                    file.Parents = new List <ParentReference> {
                        parentReference
                    };

                    file.Title         = _title;
                    file.Description   = "Created by Drive Fusion Shell Extention";
                    file.FileExtension = System.IO.Path.GetExtension(_title);
                    file.MimeType      = _mimeType;
                    file.ModifiedDate  = _lastWriteTime.ToUniversalTime();

                    _FileInfo = API.DriveService.GetFileInfo(file);

                    if (_FileInfo.IsFolder)
                    {
                        Lock();

                        using (API.DriveService.Connection connection = API.DriveService.Connection.Create())
                        {
                            FilesResource.InsertRequest request = connection.Service.Files.Insert(file);

                            request.Fields = API.DriveService.RequestFields.FileFields;

                            file = request.Execute();

                            _FileId   = file.Id;
                            _FileInfo = API.DriveService.GetFileInfo(file);

                            DriveService_ProgressChanged(UploadStatus.Completed, 0, null);
                        }
                    }
                    else
                    {
                        Lock(_filePath, System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.Read, System.IO.FileShare.ReadWrite);

                        using (API.DriveService.Connection connection = API.DriveService.Connection.Create())
                        {
                            FilesResource.InsertMediaUpload request = connection.Service.Files.Insert(file, _FileStream, _mimeType);

                            request.Fields = API.DriveService.RequestFields.FileFields;

                            request.ProgressChanged  += DriveService_ProgressChanged;
                            request.ResponseReceived += DriveService_ResponseReceived;

                            request.ChunkSize = FilesResource.InsertMediaUpload.DefaultChunkSize;

                            request.Pinned = _parameters.Pinned;
                            request.UseContentAsIndexableText = _parameters.UseContentAsIndexableText;

                            _CancellationTokenSource = new System.Threading.CancellationTokenSource();

                            System.Threading.Tasks.Task <IUploadProgress> task = request.UploadAsync(_CancellationTokenSource.Token);
                        }
                    }
                }
                catch (Exception exception)
                {
                    try
                    {
                        _Status           = StatusType.Failed;
                        _ExceptionMessage = exception.Message;

                        DriveService_ProgressChanged(UploadStatus.Failed, 0, exception);
                    }
                    catch
                    {
                        Debugger.Break();
                    }

                    Log.Error(exception);
                }
            }
        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);
        }
コード例 #19
0
        public void CreateFolder(string FullPath, string Name, string RelativePath)
        {
            if (credential == null)
            {
                SetCredential();
            }
            if (credential != null)
            {
                if (service == null)
                {
                    SetService();
                }
                if (service != null)
                {
                    if (!FolderExists(FullPath, Name, RelativePath))
                    {
                        _CurrentGoogleID = "";
                        File body = new File();
                        body.Title       = Name;
                        body.Description = Name;
                        body.MimeType    = "application/vnd.google-apps.folder";
                        string parent = GetParentId(RelativePath);
                        if (!string.IsNullOrEmpty(parent))
                        {
                            body.Parents = new List <ParentReference>()
                            {
                                new ParentReference()
                                {
                                    Id = parent
                                }
                            };
                        }

                        try
                        {
                            FilesResource.InsertRequest request = service.Files.Insert(body);
                            File file    = request.Execute();
                            Item newFold = new Item();
                            newFold.Name     = Name;
                            newFold.IsFolder = true;
                            if (!string.IsNullOrEmpty(RelativePath))
                            {
                                newFold.Path = RootFolder + "\\" + RelativePath + "\\" + Name;
                            }
                            else
                            {
                                newFold.Path = RootFolder + "\\" + Name;
                            }
                            newFold.GoogleID       = file.Id;
                            newFold.GoogleParentID = parent;
                            AddToListOnGoogleDrive(newFold);
                            _CurrentGoogleID = file.Id;
                        }
                        catch (Exception e)
                        {
                            Console.WriteLine("An error occurred: " + e.Message);
                        }
                    }
                }
            }
        }
コード例 #20
0
        public File UploadFilePath(Initializer initializer, string filePath, System.IO.MemoryStream stream)
        {
            //filepath is empty or is not a full file path
            if (string.IsNullOrEmpty(filePath) || !filePath.Contains("\\"))
            {
                return(null);
            }

            DriveService svc      = new DriveService(CreateInitializer(initializer));
            string       fileName = filePath.Substring(filePath.LastIndexOf('\\') + 1);

            //create folder path
            string[] folders     = filePath.Split('\\');
            bool     folderExist = true;
            string   fileId      = string.Empty;

            //remove filename from path
            for (int i = 0; i < folders.Length - 1; i++)
            {
                string folder = folders[i];

                //skip root
                if (folder.Contains(":"))
                {
                    continue;
                }

                //verify if the folder already exist
                if (folderExist)
                {
                    FilesResource.ListRequest listRequest = svc.Files.List();
                    listRequest.Spaces = "drive";
                    listRequest.Fields = "items(id)";
                    //Query folder name
                    listRequest.Q = "Title='" + folder + "' and mimeType='application/vnd.google-apps.folder'";
                    //get root folder id
                    if (string.IsNullOrEmpty(fileId))
                    {
                        fileId = svc.About.Get().Execute().RootFolderId;
                    }
                    listRequest.Q += " and '" + fileId + "' in parents";

                    FileList fileList = listRequest.Execute();
                    //file exist
                    if (fileList.Items != null && fileList.Items.Count > 0)
                    {
                        fileId = fileList.Items[0].Id;
                        continue;
                    }
                    else
                    {
                        folderExist = false;
                    }
                }

                //create file folder
                File fileFolder = new File();
                fileFolder.Title    = folder;
                fileFolder.MimeType = "application/vnd.google-apps.folder";
                //verfy if is the root folder
                if (!string.IsNullOrEmpty(fileId))
                {
                    fileFolder.Parents = new List <ParentReference>();
                    fileFolder.Parents.Add(new ParentReference()
                    {
                        Id = fileId
                    });
                }

                FilesResource.InsertRequest request = svc.Files.Insert(fileFolder);
                fileId = request.Execute().Id;
            }

            //insert file
            string title    = fileName;
            string mimeType = null;

            if (fileName.Contains("."))
            {
                title    = fileName.Split('.')[0];
                mimeType = GetMimeType(fileName.Split('.')[1]);
            }
            File fileMetaData = new File()
            {
                Title    = fileName.Split('.')[0],
                MimeType = mimeType,
                Parents  = new List <ParentReference>()
            };

            fileMetaData.Parents.Add(new ParentReference()
            {
                Id = fileId
            });

            FilesResource.InsertMediaUpload insertRequest = svc.Files.Insert(fileMetaData, stream, mimeType);
            insertRequest.Upload();
            return(insertRequest.ResponseBody);
        }