2

I am trying to download image from <img src="...">. If the src contains the file name and extension, I can download image simply passing url to my program.

However, when the src does not contains file name and extension, like

<img style="-webkit-user-select: none; cursor: zoom-in;" src="https://secure.somewebsite.net/website/member.php/1/folders/get_attach?mail_id=11111&amp;attach_id=1">

it is possible to download the image from C# code?

Thank you.

jkl
  • 675
  • 2
  • 8
  • 23
  • What are you using to successfully download `file name and extension` that isn't working for something like `/get_attach?mail_id=11111&attach_id=1` ? – bdimag Mar 20 '15 at 18:51
  • @bdimag i am using `webClient.DownloadFile(uri, @"C:\Users\Dev2\Downloads\img.png");` to download. Downloading it self is working but when I open it, it says the file is corrupted. – jkl Mar 20 '15 at 18:56
  • 3
    Suggest changing the extension to .TXT (or even .HTML) and open -- you're likely getting a message from the web server saying you're not permitted to hotlink or download the file directly – bdimag Mar 20 '15 at 19:00
  • 1
    The additional details you proved below should have been included with your question. The reason you are getting a corrupted image is that the server does not authorize your request. The first step to your solution would be to authorize your request and then to download the image. Follow this link to see how to create a correct request and then you can download your image. http://stackoverflow.com/questions/17183703/using-webclient-or-webrequest-to-login-to-a-website-and-access-data – Marko Mar 20 '15 at 22:21

3 Answers3

3

Here is a complete sample

using (WebClient client = new WebClient())
{
    client.DownloadFile("http://somedomain/image.png",
    @"c:\temp\image.png");

    // You can also you the async call 
    client.DownloadFileAsync("http://somedomain/image.png",
    @"c:\temp\image.png");
}
Marko
  • 2,734
  • 24
  • 24
1

Yes it is possible,

You can use these methods to download the image from c# :

client.DownloadFileAsync(new Uri(url), @"c:\temp\img.png");
client.DownloadFile(new Uri(url), @"c:\temp\img.png");
Cyka
  • 51
  • 1
  • 6
1

Now, WebClient is obselete (-> https://learn.microsoft.com/en-us/dotnet/fundamentals/syslib-diagnostics/syslib0014)

use for exemple

using var httpClient = new HttpClient();
var streamGot = await httpClient.GetStreamAsync("http://somedomain/image.png");
await using var fileStream = new FileStream("img.png", FileMode.Create, FileAccess.Write);
streamGot.CopyTo(fileStream);
NewTom
  • 109
  • 2
  • 9