본문 바로가기
.Net

.NET - Download file from HttpClient/WebClient

by 올엠 2020. 12. 15.
반응형

Http를 이용해서 파일을 다운로드해야 하는 상황에서 2가지으로 정리하여 구성할수 있다.

하나는 API를 이용하여 다운로드하는 상황, 다른 하나는 URL을 기반으로 다운로드를 하는 상황일 것이다.

해당 상황에 맞는 코드를 정리해 본다.

1. API를 이용한 다운로드

아래 코드는 API의 filename인자로 전달하여 파일을 다운로드 하는 방안이다.

FileInfo를 통해 저장할 파일의 전체 경로를 미리 구성해 놓고, 정상적인 응답이 있다면, Stream을 통해 파일을 생성하는 코드이다.

using System;
using System.IO;
using System.Net.Http;

namespace httpdownload
{
    class Program
    {
        static async System.Threading.Tasks.Task Main(string[] args)
        {
            using (var httpClient = new HttpClient())
            {
                using (var response = await httpClient.GetAsync("http://" + args[0] + "/api/download/?filename=" + args[1] + ""))
                {
                    Directory.CreateDirectory(Directory.GetCurrentDirectory() +@"\download\"+ args[1]);
                    var fileInfo = new FileInfo(Directory.GetCurrentDirectory() + @"\download\" + args[1]);
                    response.EnsureSuccessStatusCode();
                    await using var ms = await response.Content.ReadAsStreamAsync();
                    await using var fs = File.Create(fileInfo.FullName);
                    ms.Seek(0, SeekOrigin.Begin);
                    ms.CopyTo(fs);
                }
            }
        }
    }
}

1. URL를 이용한 다운로드

URL을 이용한 방식은 WebClient를 이용해서 보다 심플하게 구현이 가능하다.

using System;
using System.IO;
using System.Net;

namespace httpdownload
{
    class Program
    {
        static void Main(string[] args)
        {
            Directory.CreateDirectory(Directory.GetCurrentDirectory() +@"\download\"+ args[1]);
            var fileInfo = new FileInfo(Directory.GetCurrentDirectory() + @"\download\" + args[1]);
            WebClient webClient = new WebClient();
            webClient.DownloadFile("http://" + args[0] + "/download/" + args[1] + "", fileInfo.FullName);
        }
    }
}

 

 

 

반응형