simona a

simona a

  • NA
  • 5
  • 0

Programmatically downloading file

Jan 24 2017 11:37 PM

Using C# 4.5,I'm trying to programmatically log-on to a third-party website and then download a csv file from another page on that site. I tried using following approach.I dont get any errors but it seems to download the contents of their logon page and save it as a csv file instead of the actual csv file having data.

Also,if I read the response stream after logging in, I see that I'm getting the log-on webpage back.

What am I missing here please? Plus, I need to post the name of the form as well.How do I achieve that?Please advise.

Update:I tried using CookieContainer in request object, but still no luck..I get the same result.

Thanks.

//Log-on to website and post user and password
var request = new HttpRequestMessage(HttpMethod.Post, myLogonURL);
request.Content = new StringContent("{\"user\":\"abcd\",\"password\":test}", Encoding.UTF8, "application/x-www-form-urlencoded");
var sendTask = client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead);
var response = sendTask.Result.EnsureSuccessStatusCode();
//Download the file
request = new HttpRequestMessage(HttpMethod.Get, fileDownloadURL);
sendTask = client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead);
response = sendTask.Result.EnsureSuccessStatusCode();
var httpStream = await response.Content.ReadAsStreamAsync();
//Save the downloaded file
using (var fileStream = File.Create(downloadedFilePath))
using (var reader = new StreamReader(httpStream)) {
httpStream.CopyTo(fileStream);
fileStream.Flush();
}

Answers (1)