Exemplo n.º 1
0
        /// <summary>
        /// Downloads the file contents.
        /// </summary>
        /// <param name="documentLibraryClient">The IDocumentLibraryClient instance.</param>
        /// <param name="libraryId">The library ID.</param>
        /// <param name="path">The path to the file.</param>
        /// <param name="tenantId">Optional. Specifies which tenant to use.</param>
        /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>
        /// <returns>Either the http file stream or an error.</returns>
        public static async Task <Result <HttpFileResponse> > DownloadContentResultAsync(this IDocumentLibraryClient documentLibraryClient, Guid libraryId, CloudPath path, Guid?tenantId = null, CancellationToken cancellationToken = default)
        {
            if (documentLibraryClient is null)
            {
                throw new ArgumentNullException(nameof(documentLibraryClient));
            }

            HttpResponseMessage response = await documentLibraryClient.DownloadContentHttpResponseAsync(libraryId, path, tenantId, cancellationToken).ConfigureAwait(false);

            switch (response.StatusCode)
            {
            case HttpStatusCode.OK:
            {
                Result <HttpFileResponse> fileResponse = await HttpFileResponse.CreateAsync(response).ConfigureAwait(false);

                return(fileResponse);
            }

            case HttpStatusCode.NoContent:
                response.Dispose();
                return(default);

            case HttpStatusCode.BadRequest:
            case HttpStatusCode.InternalServerError:
            {
                try
                {
                    if (response.IsContentProblem())
                    {
                        HttpProblem problem = await response.DeserializeJsonContentAsync <HttpProblem>().ConfigureAwait(false);

                        return(new HttpProblemError(problem).ToResult <HttpFileResponse>());
                    }
                    else
                    {
                        ErrorResponse errorResponse = await response.DeserializeJsonContentAsync <ErrorResponse>().ConfigureAwait(false);

                        return(errorResponse.Error.ToResult <HttpFileResponse>());
                    }
                }
                finally
                {
                    response.Dispose();
                }
            }

            default:
            {
                UnexpectedStatusCodeError error = await UnexpectedStatusCodeError.CreateAsync(response, $"{nameof(IDocumentLibraryClient)}.{nameof(DownloadContentResultAsync)}").ConfigureAwait(false);

                response.Dispose();
                return(error.ToResult <HttpFileResponse>());
            }
            }
        }