Ali Kazmi Ali Kazmi - 1 month ago 8x
ASP.NET (C#) Question

Download Image File from a cdn URL

I am trying to download a file from Following url in
Applying this url as src in img tag works fine but i need to save this image in my download folder.

I tried WebClient.Download method, Downloaddata and webrequest methods but they returned 403 forbidden error


Try using WebRequest like this: (you have to specify your download folder and links accordingly I guess)

string lnk = @"";
WebRequest request = HttpWebRequest.Create(lnk);
((HttpWebRequest)request).AllowAutoRedirect = true;
((HttpWebRequest)request).UserAgent = @"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)";
int dataLength;
int bytesRead;
int wroteSoFar = 0;
var response = request.GetResponse();
Stream responseStream = response.GetResponseStream();

byte[] buffer = new byte[1024];
using (FileStream oFile = new FileStream(Path.Combine(Environment.CurrentDirectory, @"img.jpg"), FileMode.Append, FileAccess.Write))
    dataLength = (int)response.ContentLength;
        bytesRead = responseStream.Read(buffer, 0, buffer.Length);
        oFile.Write(buffer, 0, bytesRead);
        wroteSoFar += bytesRead;
        //Console.WriteLine($"{(wroteSoFar / 1000).ToString("N0")} KB / {(dataLength / 1000).ToString("N0")} KB");
    while (bytesRead != 0);

I managed to download it like this.