コード例 #1
0
        /// <summary>
        /// Download file from google drive
        /// </summary>
        /// <param name="fileId">Downloaded file ID</param>
        /// <returns>Server file path in server</returns>
        public static async Task <string> DownloadFileAsync(string fileId)
        {
            FilesResource.GetRequest request = GetGoogleDriveService().Files.Get(fileId);

            string fileName = request.Execute().Name;
            string filePath = Path.Combine(Path.GetTempPath(), fileName);

            MemoryStream stream = new MemoryStream();

            request.MediaDownloader.ProgressChanged += progress =>
            {
                switch (progress.Status)
                {
                case DownloadStatus.Completed:
                    SaveFile(stream, filePath);
                    break;

                case DownloadStatus.Downloading:
                case DownloadStatus.Failed:
                    break;
                }
            };

            await request.DownloadAsync(stream);

            return(filePath);
        }
コード例 #2
0
            public async Task FillPipeAsync(PipeWriter writer, CancellationToken cancellationToken)
            {
                try
                {
                    var pipe = new Pipe();
                    using var pushStream = pipe.Writer.AsStream();
                    var progressTask = fileInfoRequest.DownloadAsync(pushStream, cancellationToken);
                    using var pullStream = pipe.Reader.AsStream();
                    var pipingTask = handler.FillPipeAsync(pullStream, writer, cancellationToken);
                    var result     = await progressTask.ConfigureAwait(false);

                    if (result.Status != DownloadStatus.Completed)
                    {
                        Config.Log.Error(result.Exception, "Failed to download file from Google Drive: " + result.Status);
                    }
                    await pipe.Writer.FlushAsync(cancellationToken).ConfigureAwait(false);

                    pipe.Writer.Complete();
                    await pipingTask.ConfigureAwait(false);
                }
                catch (Exception e)
                {
                    Config.Log.Error(e, "Failed to download file from Google Drive");
                }
            }
コード例 #3
0
        public async Task <MemoryStream> DownloadFile(string Id)
        {
            MemoryStream downloadedFile = new MemoryStream();

            FilesResource.GetRequest getRequest = service.Files.Get(Id);
            await getRequest.DownloadAsync(downloadedFile);

            return(downloadedFile);
        }
コード例 #4
0
        public static FilesResource.GetRequest StartDownload(string id, System.IO.FileStream fileStream, CancellationToken cancellationToken)
        {
            FilesResource.GetRequest downlodRequest = new FilesResource.GetRequest(Service, id);

            downlodRequest.MediaDownloader.ChunkSize = ResumableUpload.MinimumChunkSize;

            downlodRequest.DownloadAsync(fileStream, cancellationToken);

            return(downlodRequest);
        }
コード例 #5
0
        /// <summary>
        /// Downloads a remote file from Google Drive, as a readable stream.
        /// </summary>
        /// <param name="fullFilename">The Id of the remote file to download from Google Drive.</param>
        /// <returns>Returns a readable stream representing the remote file to download.</returns>
        public async Task <Stream> Download(string fullFilename)
        {
            var stream = new MemoryStream();

            FilesResource.GetRequest request = driveService.Files.Get(fullFilename);

            await request.DownloadAsync(stream);

            return(stream);
        }
コード例 #6
0
        public async Task <bool> DownloadFile(string Id, string file)
        {
            FileStream downloadedFile = new FileStream(file, FileMode.Create);

            FilesResource.GetRequest getRequest = service.Files.Get(Id);
            await getRequest.DownloadAsync(downloadedFile);

            downloadedFile.Close();
            return(true);
        }
コード例 #7
0
        /// <summary>
        /// Asynchronously downloads the file.
        /// </summary>
        /// <returns></returns>
        /// <exception cref="System.IO.FileNotFoundException"></exception>
        protected override async Task <SerializableAPIResult <CloudStorageServiceAPIFile> > DownloadFileAsync()
        {
            SerializableAPIResult <CloudStorageServiceAPIFile> result = new SerializableAPIResult <CloudStorageServiceAPIFile>();

            try
            {
                m_fileId = m_fileId ?? await GetFileIdAsync().ConfigureAwait(false);

                if (string.IsNullOrWhiteSpace(m_fileId))
                {
                    throw new FileNotFoundException();
                }

                using (DriveService client = GetClient())
                    using (Stream stream = new MemoryStream())
                    {
                        FilesResource.GetRequest request = client.Files.Get(m_fileId);
                        request.Fields = "id, name";

                        IDownloadProgress response = await request.DownloadAsync(stream).ConfigureAwait(false);

                        if (response.Exception == null)
                        {
                            return(await GetMappedAPIFileAsync(result, stream));
                        }

                        result.Error = new SerializableAPIError {
                            ErrorMessage = response.Exception.Message
                        };
                    }
            }
            catch (GoogleApiException exc)
            {
                result.Error = new SerializableAPIError {
                    ErrorMessage = exc.Error.Message
                };
            }
            catch (TokenResponseException exc)
            {
                IsAuthenticated = false;
                result.Error    = new SerializableAPIError {
                    ErrorMessage = exc.Error.ErrorDescription ?? exc.Error.Error
                };
            }
            catch (Exception exc)
            {
                result.Error = new SerializableAPIError {
                    ErrorMessage = exc.Message
                };
            }

            return(result);
        }
コード例 #8
0
        public async Task <VersionedData> GetRemoteData()
        {
            var remoteStorageInfo = await _remoteStorageInfoRepository.GetRemoteStorageInfo();

            FilesResource.GetRequest request = _service.Files.Get(remoteStorageInfo.Id);
            using (var stream = new MemoryStream())
            {
                var rc = await request.DownloadAsync(stream);

                stream.Seek(0, SeekOrigin.Begin);
                using (var sr = new StreamReader(stream))
                {
                    string data = await sr.ReadToEndAsync();

                    Console.WriteLine(data);
                    return(JsonConvert.DeserializeObject <VersionedData>(data));
                }
            }
        }
コード例 #9
0
        public static async Task <bool> DownloadGoogleFile(File f, string fileName)
        {
            if (!Storage.xs.Settings.IsGDriveOn())
            {
                return(false);
            }

            var stream = new System.IO.MemoryStream();

            try
            {
                FilesResource.GetRequest req = _service.Files.Get(f.Id);
                await req.DownloadAsync(stream);
            }
            catch (Exception)
            {
                return(false);
            }

            Storage.xs.CreateEmptyIfNeeded(fileName);
            System.IO.FileStream file = new System.IO.FileStream(fileName, System.IO.FileMode.Truncate, System.IO.FileAccess.Write);

            try
            {
                stream.WriteTo(file);
            }
            catch (Exception)
            {
                return(false);
            }
            finally
            {
                file.Close();
                stream.Close();
            }

            return(true);
        }
コード例 #10
0
        /// <summary>
        /// Reads the file line data asynchronous.
        /// </summary>
        /// <param name="fileName">Name of the file.</param>
        /// <param name="fileId">The file identifier.</param>
        /// <param name="mime">The MIME.</param>
        /// <returns>
        /// The file contents line by line.
        /// </returns>
        public async Task <IList <string> > ReadFileLineDataAsync(string fileName, string fileId, string mime)
        {
            FilesResource.GetRequest request = _driveService.Files.Get(fileId);
            IList <string>           results = new List <string>();

            await using MemoryStream stream = new MemoryStream();
            IDownloadProgress progress = await request.DownloadAsync(stream).ConfigureAwait(false);

            if (progress.Status == DownloadStatus.Completed)
            {
                if (!Directory.Exists("tempfiles"))
                {
                    Directory.CreateDirectory("tempfiles");
                }

                string outputPath = $"tempfiles/{fileName}";

                await using (FileStream file = new FileStream(outputPath, FileMode.Create, FileAccess.Write))
                {
                    stream.WriteTo(file);
                }

                if (System.IO.File.Exists(outputPath))
                {
                    results = await System.IO.File.ReadAllLinesAsync(outputPath).ConfigureAwait(false);

                    System.IO.File.Delete(outputPath);
                }

                return(results);
            }
            else
            {
                // TODO log
            }

            return(results);
        }
コード例 #11
0
        public async Task <ActionResult> DownloadFileDrive(string code)
        {
            List <dtoAsuntos> Archivos = (List <dtoAsuntos>)Session["ArchivosDownloadDrive"];

            try
            {
                string        IdUsuario   = User.Identity.GetUserId();
                string        redirectUrl = $"https://{Request.Url.Host}:{Request.Url.Port}/{Url.Action(nameof(this.DownloadFileDrive)).TrimStart('/')}";
                string        path        = Server.MapPath("~/client_secrets.json");
                ClientSecrets Secrets     = null;
                using (var filestream = new FileStream(path, FileMode.Open, FileAccess.Read))
                {
                    Secrets = GoogleClientSecrets.Load(filestream).Secrets;
                }
                var initializer = new GoogleAuthorizationCodeFlow.Initializer()
                {
                    ClientSecrets = Secrets,
                    Scopes        = Scopes,
                };
                int UserIdPersona = 0;


                var googleCodeFlow = new GoogleAuthorizationCodeFlow(initializer);
                var token          = googleCodeFlow.ExchangeCodeForTokenAsync(UserIdPersona != 0 ? UserIdPersona.ToString() : Session["IdUsuario"].ToString(), code, redirectUrl, CancellationToken.None).Result;
                //var resultMVC = new AuthorizationCodeWebApp(googleCodeFlow, redirectUrl, redirectUrl).AuthorizeAsync(UserId.ToString(), CancellationToken.None).Result;
                UserCredential credential = new UserCredential(googleCodeFlow, UserIdPersona != 0 ? UserIdPersona.ToString() : Session["IdUsuario"].ToString(), token);
                DriveService   service    = new DriveService(new BaseClientService.Initializer
                {
                    HttpClientInitializer = credential,
                    ApplicationName       = Application_Name,
                    ApiKey = "AIzaSyBtEx9nIXbv-C-jEj45iIUZvs-HUP8SCc8"
                });
                foreach (dtoAsuntos FileId in Archivos)
                {
                    FilesResource.GetRequest request = service.Files.Get(FileId.GuidArchivo);

                    string destPath = Path.Combine(Server.MapPath("~/App_Data"), FileId.NombreArchivo);
                    using (FileStream filestream = new FileStream(destPath, FileMode.Create, FileAccess.Write))
                    {
                        request.MediaDownloader.ProgressChanged +=
                            (IDownloadProgress progress) =>
                        {
                            switch (progress.Status)
                            {
                            case DownloadStatus.Downloading:
                            {
                                Debug.WriteLine(progress.BytesDownloaded);
                                break;
                            }

                            case DownloadStatus.Completed:
                            {
                                Debug.WriteLine("Download complete.");
                                break;
                            }

                            case DownloadStatus.Failed:
                            {
                                Debug.WriteLine("Download failed.");
                                break;
                            }
                            }
                        };
                        await request.DownloadAsync(filestream);
                    }
                    byte[] Blob = System.IO.File.ReadAllBytes(destPath);
                    FileId.Archivo     = Blob;
                    FileId.GuidArchivo = String.Empty;
                    FileId.IdUsuario   = IdUsuario;
                }
                Tuple <bool, string> _result = new BALAsuntos().UpdateArchivosAsuntos(Archivos);

                foreach (dtoAsuntos file in Archivos)
                {
                    string destPath = Path.Combine(Server.MapPath("~/App_Data"), file.NombreArchivo);
                    System.IO.File.Delete(destPath);
                }

                Session["ArchivosDownloadDrive"] = null;
                if (_result.Item1)
                {
                    Session["ArchivosDownloadDrive"] = true;
                }
            }
            catch (Exception ex)
            {
            }
            return(RedirectToAction("MisAsuntos"));
        }
コード例 #12
0
 public async Task DownloadFileAsync(string fileId, Stream stream)
 {
     FilesResource.GetRequest getRequest = service.Files.Get(fileId);
     await getRequest.DownloadAsync(stream);
 }