コード例 #1
0
        /// <inheritdoc />
        /// <param name="parentFolderId">This is the parent folder id.</param>
        /// <param name="pageSize">Items per page.</param>
        /// <param name="pageObject">Page token.</param>
        /// <exception cref="FileNotFoundException">Files not found.</exception>
        /// <exception cref="InvalidDataException"><paramref name="pageObject"/> is not a <see cref="string"/>.</exception>
        /// <exception cref="UnauthorizedAccessException">Unauthorized token.</exception>
        public async Task <ListFileInfoResult> ListAsync(string parentFolderId = "", int pageSize = 100, object pageObject = default)
        {
            if (!(pageObject is string))
            {
                throw new InvalidDataException($"'{nameof(pageObject)}' must be a string.");
            }

            string nextPageToken = default;
            IList <Google.Apis.Drive.v3.Data.File> files = default;

            try
            {
                var request = Service.Files.List();
                request.Fields    = "nextPageToken, files(id, name, mimeType, createdTime, size)";
                request.PageSize  = pageSize;
                request.PageToken = (string)pageObject;

                if (!string.IsNullOrWhiteSpace(parentFolderId))
                {
                    request.Q = $"'{parentFolderId}' in parents and ";
                }
                // ignore files in trash
                request.Q = "trashed = false";

                var result = await request.ExecuteAsync();

                nextPageToken = result.NextPageToken;
                files         = result.Files;

                if (files?.Count == 0)
                {
                    throw new FileNotFoundException("Files not found.");
                }

                var resultFiles = new ListFileInfoResult();

                files.ForEach(file =>
                {
                    var fileInfo = new FileInfoResult
                    {
                        MimeType    = file.MimeType,
                        Id          = file.Id,
                        Name        = file.Name,
                        CreatedTime = file.CreatedTime,
                        Size        = file.Size ?? 0,
                    };

                    resultFiles.Files.Add(fileInfo);
                });

                resultFiles.NextPageObject = nextPageToken;
                return(resultFiles);
            }
            catch (TokenResponseException e)
                when(e.Message.Contains("unauthorized", StringComparison.InvariantCultureIgnoreCase))
                {
                    throw new UnauthorizedAccessException("Unauthorized", e);
                }
            catch { throw; }
        }
コード例 #2
0
        /// <summary>
        /// List all directories/files from a <see cref="FtpSettings.Url"/> in a <paramref name="relativeDirectory"/>.
        /// </summary>
        /// <remarks>
        /// <para><paramref name="relativeDirectory"/> is optional, if is not specified lists in the root <see cref="FtpSettings.Url"/>.</para>
        /// <para><paramref name="relativeDirectory"/> can also be specified in <see cref="FtpSettings.Url"/>.</para>
        /// </remarks>
        /// <param name="relativeDirectory">Optional: relative directory path.</param>
        /// <param name="pageSize">Not used.</param>
        /// <param name="pageObject">Not used.</param>
        /// <returns>A <see cref="System.Collections.IEnumerable"/> of string listing all directories and files.</returns>
        /// <exception cref="WebException">Fail when connecting to the ftp server.</exception>
        /// <exception cref="UnauthorizedAccessException">Unauthorized: invalid credentials.</exception>
        public async Task <ListFileInfoResult> ListAsync(
            string relativeDirectory = "",
            int pageSize             = 100, object pageObject = default)
        {
            var uri = new Uri(_settings.Host);

            if (!string.IsNullOrWhiteSpace(relativeDirectory))
            {
                uri = new Uri(uri, relativeDirectory);
            }

            var request = (FtpWebRequest)WebRequest.Create(uri);

            try
            {
                request.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
                if (_settings.IsCredentialsAvailable)
                {
                    request.Credentials = _credentials;
                }

                using (var response = (FtpWebResponse)await request.GetResponseAsync())
                    using (var responseStream = response.GetResponseStream())
                    {
                        using (var reader = new StreamReader(responseStream))
                        {
                            var filesList = new ListFileInfoResult();
                            while (reader?.EndOfStream == false)
                            {
                                var line = reader.ReadLine();
                                var name = line.Split(" ").Last();
                                if (name == "." || name == "..")
                                {
                                    continue;
                                }

                                string contentType = "application/octet-stream";
                                new FileExtensionContentTypeProvider().TryGetContentType(name, out contentType);

                                var filesInfo = new FileInfoResult
                                {
                                    Additional = line,
                                    Name       = name,
                                    MimeType   = contentType
                                };

                                filesList.Files.Add(filesInfo);
                            }
                            return(filesList);
                        }
                    }
            }
            // 530 means not logged in
            catch (WebException e)
                when(e.Message.Contains("530"))
                {
                    throw new UnauthorizedAccessException("Unauthorized: invalid credentials.");
                }
            catch (Exception e)
            {
                throw new WebException("Fail when connecting to the ftp server.", e);
            }
            finally
            {
                request.Abort();
            }
        }