public void UploadFile(GoogleDriveMetaDataModel dataFile)
        {
            Google.Apis.Drive.v3.Data.File file = new Google.Apis.Drive.v3.Data.File();
            file.Name        = dataFile.Name;
            file.Description = dataFile.Description;
            file.MimeType    = dataFile.MimeType;
            file.Parents     = new List <string>();
            if (string.IsNullOrEmpty(dataFile.ParentFolderId) == false)
            {
                file.Parents.Add(dataFile.ParentFolderId);
            }

            byte[] byteArray = System.IO.File.ReadAllBytes(dataFile.FileName);
            System.IO.MemoryStream stream = new System.IO.MemoryStream(byteArray);

            var uploadedFile = driveService.Files.Create(file, stream, dataFile.MimeType);

            Google.Apis.Drive.v3.FilesResource.CreateMediaUpload request = driveService.Files.Create(file, stream, dataFile.MimeType);
            request.ChunkSize = 1024 * 1024;
            request.Upload();
        }
Exemplo n.º 2
0
        /// <summary>
        /// Создание нового файла
        /// </summary>
        /// <param name="name">Имя</param>
        /// <param name="value">Поток данных для записи</param>
        /// <param name="id">Ид созданного файла</param>
        /// <returns></returns>
        public bool FileCreate(string name, MemoryStream value, out string id)
        {
            bool result = false;

            id = null;
            if (credential == null)
            {
                this.Authorize();
            }
            if (credential == null)
            {
                return(result);
            }

            using (var service = new Google.Apis.Drive.v3.DriveService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName = ApplicationName,
            }))

            {
                var body = new Google.Apis.Drive.v3.Data.File();
                body.Name     = name;
                body.MimeType = "text/json";
                body.ViewersCanCopyContent = true;

                //byte[] byteArray = Encoding.Default.GetBytes(value);
                //using (var stream = new System.IO.MemoryStream(byteArray))
                //{
                Google.Apis.Drive.v3.FilesResource.CreateMediaUpload request = service.Files.Create(body, value, body.MimeType);
                if (request.Upload().Exception == null)
                {
                    id = request.ResponseBody.Id; result = true;
                }
                //}
            }
            return(result);
        }
        private static GoogleDriveResultWithData <GoogleDriveFile> UploadRequest(Google.Apis.Drive.v3.FilesResource.CreateMediaUpload request)
        {
            var status = request.Upload();

            if (status.Status == UploadStatus.Completed)
            {
                var file = request.ResponseBody;
                if (file != null)
                {
                    return(new GoogleDriveResultWithData <GoogleDriveFile>()
                    {
                        Data = new GoogleDriveFile(file.Id, file.Name, file.Description, file.WebViewLink),
                        IsSucceed = true
                    });
                }
                else
                {
                    return new GoogleDriveResultWithData <GoogleDriveFile>()
                           {
                               IsSucceed = false, ErrorInfo = new GoogleDriveErrorInfo {
                                   ErrorMessage = "Unknown error"
                               }
                           }
                };
            }

            var result = new GoogleDriveResultWithData <GoogleDriveFile>();

            if (result.FillFromException(status.Exception))
            {
                return(result);
            }
            throw status.Exception;
        }

        const string FolderMimeType = "application/vnd.google-apps.folder";
Exemplo n.º 4
0
        static void загрузитьНаДиск()
        {//object sender, EventArgs e
            UserCredential credential;

            try
            {
                FileStream str = new FileStream("client_secret.json", FileMode.Open, FileAccess.Read);
                using (var 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();

                    string exeDir    = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
                    int    firstTime = 0;
                    string folder    = null;
                    do
                    {
                        if (firstTime == 0)
                        {
                            folder = @"\базы";
                        }
                        else
                        {
                            folder = @"\нормативы";
                        }
                        string   path      = exeDir + folder;
                        string[] file_list = System.IO.Directory.GetFiles(path, "*.xls");

                        //создаём папку
                        var fileMetadata1 = new Google.Apis.Drive.v3.Data.File()
                        {
                            Name     = DateTime.Now.ToString() + "_" + System.Environment.MachineName.ToString() + "_" + folder,
                            MimeType = "application/vnd.google-apps.folder"
                        };
                        var request1 = service.Files.Create(fileMetadata1);
                        request1.Fields = "id";
                        var google_folder = request1.Execute();
                        Console.WriteLine("Файлы будут помещены в папку: " + fileMetadata1.Name); //+google_folder.id
                        Console.WriteLine("{0} | {1} файлов", folder, file_list.Length);


                        if (file_list.GetLength(0) > 0)
                        {
                            //Google.Apis.Drive.v3.Data.File body = new Google.Apis.Drive.v3.Data.File();

                            Google.Apis.Drive.v3.Data.File body = new Google.Apis.Drive.v3.Data.File()
                            {
                                Name    = "tablesheet",
                                Parents = new List <string>
                                {
                                    google_folder.Id
                                }
                            };

                            //поочереди загружаем файлы
                            for (int i = 0; i < file_list.Length; i++)
                            {
                                body.Name        = System.IO.Path.GetFileName(file_list[i]);
                                body.Description = "Описание";
                                if (Path.GetExtension(file_list[i]) == ".xls")
                                {
                                    body.MimeType = "application/vnd.ms-excel";
                                }
                                if (Path.GetExtension(file_list[i]) == ".xlsx")
                                {
                                    body.MimeType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
                                }
                                if (Path.GetExtension(file_list[i]) != ".xls" && Path.GetExtension(file_list[i]) != ".xlsx")
                                {
                                    continue;
                                }

                                Console.WriteLine("Name:{0} , Type:{1}", body.Name, body.MimeType);
                                byte[] byteArray = System.IO.File.ReadAllBytes(file_list[i]);
                                System.IO.MemoryStream stream2 = new System.IO.MemoryStream(byteArray);
                                Google.Apis.Drive.v3.FilesResource.CreateMediaUpload request = service.Files.Create(body, stream2, body.MimeType);
                                if (request.Upload().Exception != null)
                                {
                                    Console.Write(request.Upload().Exception.Message);
                                    Console.Read();
                                }
                                else
                                {
                                    Console.WriteLine("Файл успешно загружен");
                                }
                            }
                            Console.WriteLine();
                        }
                        firstTime++;
                    }while (firstTime < 2);
                }
            }

            catch (Exception x)
            { Console.WriteLine(x.Message); }
        } //the end