Share via


Accessing a server which requires authentication to download a file

Question

Monday, July 15, 2013 12:22 PM

I have a server which requires authentication (username and password). I use the WebClient class object to download a file from this server:

WebClient obj = new WebClient();
obj.DownloadFile(url,destination_file);

This code is inside the try catch block, so when i try to download, it fails and throws an exception which is caught by my catch block. When the exception is caught, i come to know that the server requires authentication. My application then creates a dialog and displays it to the user. This dialog has only two text boxes which ask the username and password to access the server. When the user enters the information, my application again tries to download the file after setting:

obj.Credentials = new NetworkCredentials(username, password);
and then calls:
obj.DownloadFile(url,destination_file);

This time the file downloads successfully. Now the problem is if I close my application and next time run it again to download another file from the same server, I don't want user to enter the username and password again to access that server. It should automatically detect that user had entered the password for the same server earlier and should use the same credentials to download the file. I don't have much knowledge in this regard but i feel this should be possible with cookies. Let me know if there is any better/standard way to achieve this.

My application is a C#.Net windows forms application and NOT ASP.Net Application.

Himanshu Saxena

All replies (3)

Monday, July 15, 2013 12:34 PM ✅Answered

Are you sure you want to store a username and password combination in plain text? It can and has been done, just want you to consider the potential security threats that can have. I personally think that if you don't want to continue to ask for username or password, then you should have the application use a default account in code. 

These are just my opinions.


Monday, July 15, 2013 12:58 PM ✅Answered

You can try to collect cookies from the web site by using CookieContainer.

Here you can find an interesting code snippet:

http://stackoverflow.com/questions/1777221/using-cookiecontainer-with-webclient-class


Monday, July 15, 2013 1:31 PM ✅Answered

Hi,

You could reuse the Windows Credential Manager. It will provide the same service than the one you have in IE that is to enter id/password with an optional "remember" option.

Try http://www.developerfusion.com/code/4693/using-the-credential-management-api/ or search in Google for c# and CredUIConfirmCredentials/CredUIPromptForCredentials for similar content...

Please always mark whatever response solved your issue so that the thread is properly marked as "Answered".