user31673
user31673

Reputation: 13695

How to call url with basic authentication inside application

I need to create an application (ASP.NET or WinForms or Windows Service, not sure) that needs to make a call to a url including username and password for basic authentication and have the url return a csv file. I then need to use the csv file in the application. I don't know how to do this. How do I call the url in my app. There can be no user interaction, it needs to be completely automated in the returning of the csv file.

Upvotes: 2

Views: 4238

Answers (2)

Peter
Peter

Reputation: 12711

Try something like this:

var webClient = new WebClient();
webClient.Credentials = new NetworkCredential("username", "password");
webClient.DownloadFile("http://someurl/file.csv", "c:\\file.csv");

Upvotes: 4

kbrimington
kbrimington

Reputation: 25642

Try out the System.Net.WebRequest class. Here is a page showing general usage:

http://msdn.microsoft.com/en-us/library/system.net.webrequest.aspx

You can swap out the assignment of the Credentials property with your own NetworkCredential object to pass a custom user name and password.

I actually handle the class a little differently than the example. I ensure that every class that is IDisposable is initialized in a using statement to avoid accidentally leaving unclaimed resources. This is especially important if your service will receive frequent or rapid traffic.

Edit:

If you're interested in a CSV parsing library, there are many you can find from any search. You might like the code from this CodeProject article. This library is flexible enough to handle properly-escaped multi-line fields.

Good luck!

Upvotes: 0

Related Questions