I'm trying to write a code to download an XLSX (Excel 2007+) file by using WebClient
in C#. The problem is, although the below (standard) code can download other files from the internet, it can't download this file, which is generated on the fly from the response of an ASPX page.
Here is my code:
public bool Download(string url, string targetFileName, out DownloadFinalState finalState)
{
finalState = DownloadFinalState.InitialState;
try
{
Random rnd = new Random();
string fname = Directory.GetCurrentDirectory() + "\\" + rnd.Next(10000, 99999) + targetFileName;
WebClient Client = new WebClient();
var ua = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)";
Client.Headers.Add(HttpRequestHeader.UserAgent, ua);
Client.DownloadFile(url, fname);
if (File.Exists(fname))
{
finalState = DownloadFinalState.FileDownloadedSuccessfully;
}
else
{
finalState = DownloadFinalState.NoExceptionButNoFile;
}
return true;
}
catch (Exception ex)
{
finalState = DownloadFinalState.ExceptionRaised;
return false;
}
}
and Here is the file's URL (which is publicly available): http://www.tsetmc.com/tsev2/excel/MarketWatchPlus.aspx?d=0
I also tried removing agent in headers and also tried HttpWebRequest
-based method but none of them worked. In the case of above code, the file being downloaded in 4KB smaller than the actual file and is in a weird unreadable (for MS Excel) format.