Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
404 views
in Technique[技术] by (71.8m points)

c# - The notorious yet unaswered issue of downloading a file when windows security is required

There is a web site: http://site.domain.com which prompts for credentials with "windows security" dialog box. So I managed to use WebBrowser control to navigate to the page and send keystrokes to enter the password - I could not find another way around.

Now I came to the point where the website generates a link to a file I want to download, it looks like: http://site.domain.com/operations/reporting/csv/Report720_2553217.csv

I tried to use WebClient to download the file but it does nothing (br is my WebBrowser control):

WebClient wb = new WebClient();
wb.Headers.Add( br.Document.Cookie);
wb.DownloadFile(link, @"report.csv");

I have been trying to find a working solution to no avail. I know the web client is not authenticated so tried to use web browser's cookie but it does not work. The cookie looks as follows:

TLTUID=61FE48D8F9B910F9E930F42D6A03EAA6; TLTSID=0B2B8EE82688102641B7E768807FA8B2; s_cc=true; s_sq=%5B%5BB%5D%5D; ASPSESSIONIDQQSTRDQS=FNPJCODCEMGFIDHFLKDBEMHO

So I have two questions:

  1. How to allow web client to download a file accessible from web browser's session. What am I doing wrong in the above code sample?

  2. Is there an easy way to use WebBrowser solely to download and save that file to the path and filename of my choice? Or how to do it all using WebClient or something else?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
  1. Not possible, AFAIK. WebClient and WebBrowser use different layers to access web. WebClient uses WinHTTP, WebBrowser uses UrlMon. Thus, they would have separate sessions (including the authentication cache).

  2. That's possible, just use any of UrlMon APIs to download the file, e.g. URLDownloadToFile or URLDownloadToCacheFile. I've just answered a similar question.

On a side note, you don't have to feed in keystrokes to provide authentication credentials. You can implement IAuthenticateEx on WebBrowser site object for this. Here is more info.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...