How to use httpwebrequest to pull image from website to local file

前端 未结 4 1725
粉色の甜心
粉色の甜心 2020-11-27 07:29

I\'m trying to use a local c# app to pull some images off a website to files on my local machine. I\'m using the code listed below. I\'ve tried both ASCII encoding and UTF

4条回答
  •  半阙折子戏
    2020-11-27 07:52

    A variation of the answer, using async await for async file I/O. See Async File I/O on why this is important.

    Download png and write to disk using BinaryReader/Writer

    string outFile = System.IO.Path.Combine(outDir, fileName);
    
    // Download file
    var request = (HttpWebRequest) WebRequest.Create(imageUrl);
    
    using (var response = await request.GetResponseAsync()){
        using (var reader = new BinaryReader(response.GetResponseStream())) {
    
            // Read file 
            Byte[] bytes = async reader.ReadAllBytes();
    
            // Write to local folder 
            using (var fs = new FileStream(outFile, FileMode.Create)) {
                await fs.WriteAsync(bytes, 0, bytes.Length);
            }
        }
    }
    

    Read all bytes extension method

    public static class Extensions {
    
        public static async Task ReadAllBytes(this BinaryReader reader)
        {
            const int bufferSize = 4096;
            using (var ms = new MemoryStream())
            {
                byte[] buffer = new byte[bufferSize];
                int count;
                while ((count = reader.Read(buffer, 0, buffer.Length)) != 0) {
                    await ms.WriteAsync(buffer, 0, count);
                }
                return ms.ToArray();
            }
        }
    }
    

提交回复
热议问题