Q:

How to Download a file from a website programatically c#

I am developing a application for downloading mcx data from the website.It would be good if i 
myself create an application and use it.
There is a datetimepicker in the website in which I want to select the date programatically 
click the go button and later view in excel.when I click view on excel it downloads the file 
of the data of the particular date. You can see this link and understand what i want to say.
http://www.mcxindia.com/sitepages/bhavcopy.aspx
There would be a great appreciation if someone could help me.
Thanks In Avance.

A:

using System.Net;

WebClient webClient = new WebClient();
webClient.DownloadFile("http://mysite.com/myfile.txt", @"c:\myfile.txt");

but if the file is too large then you should use the async method.
check this code example http://www.csharp-examples.net/download-files/

A:

You'll need to post your data to the server with your client request as explained by @Peter.  
This is an ASP.net page, and therefore it requires that you send some data on postback in order to complete the callback.  
Using google, I was able to find this as a proof of concept.  
The following is a snippet I wrote in Linqpad to test it out.  Here it is:
void Main()
{

    WebClient webClient = new WebClient();

    byte[] b = webClient.DownloadData("http://www.mcxindia.com/sitepages/BhavCopyDateWise.aspx");

    string s = System.Text.Encoding.UTF8.GetString(b);

    var __EVENTVALIDATION = ExtractVariable(s, "__EVENTVALIDATION");

    __EVENTVALIDATION.Dump();

    var forms = new NameValueCollection(); 

    forms["__EVENTTARGET"] = "btnLink_Excel";
    forms["__EVENTARGUMENT"] = "";
    forms["__VIEWSTATE"] = ExtractVariable(s, "__VIEWSTATE");
    forms["mTbdate"] = "11%2F15%2F2011";
    forms["__EVENTVALIDATION"] = __EVENTVALIDATION;

    webClient.Headers.Set(HttpRequestHeader.ContentType, "application/x-www-form-urlencoded");

    var responseData = webClient.UploadValues(@"http://www.mcxindia.com/sitepages/BhavCopyDateWise.aspx", "POST", forms); 
    System.IO.File.WriteAllBytes(@"c:\11152011.csv", responseData);
}

private static string ExtractVariable(string s, string valueName)
{
     string tokenStart = valueName + "\" value=\"";
     string tokenEnd = "\" />";

     int start = s.IndexOf(tokenStart) + tokenStart.Length;
     int length = s.IndexOf(tokenEnd, start) - start;
     return s.Substring(start, length);
}

