C# Webclient Stream download file from FTP to local storage

前端 未结 1 1555
梦如初夏
梦如初夏 2020-12-17 02:11

I\'ve been downloading files from an FTP server via the WebClient object that the .NET namespace provides and then write the bytes to a actual file

相关标签:
1条回答
  • 2020-12-17 02:12

    Have you tried the following usage of WebClient class?

    using (WebClient webClient = new WebClient())
    {
        webClient.DownloadFile("url", "filePath");
    }
    

    Update

    using (var client = new WebClient())
    using (var stream = client.OpenRead("..."))
    using (var file = File.Create("..."))
    {
        stream.CopyTo(file);
    }
    

    If you want to download file explicitly using customized buffer size:

    public static void DownloadFile(Uri address, string filePath)
    {
        using (var client = new WebClient())
        using (var stream = client.OpenRead(address))
        using (var file = File.Create(filePath))
        {
            var buffer = new byte[4096];
            int bytesReceived;
            while ((bytesReceived = stream.Read(buffer, 0, buffer.Length)) != 0)
            {
                file.Write(buffer, 0, bytesReceived);
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题