I need to download a file attached to a URL using C# and I have written this piece of code:
var uri = new Uri("http://members.tsetmc.com/tsev2/excel/MarketWatchPlus.aspx?d=0");
var request = WebRequest.CreateHttp(uri);
var response = request.GetResponse();
string disposition = response.Headers["Content-Disposition"];
string filename = disposition.Substring(disposition.IndexOf("filename=") + 9).Replace("\"", "");
using (var fs = new FileStream(filename.Replace("/", "-"), FileMode.Create, FileAccess.Write, FileShare.None))
{
response.GetResponseStream().CopyTo(fs);
}
But the excel file saved in the path seems to be corrupted
I get a forbidden back when trying to call your URL. In my example I have used a different URL which is working fine.
var request = WebRequest.CreateHttp("http://spreadsheetpage.com/downloads/xl/king-james-bible.xlsm");
var response = request.GetResponse();
using (var fs = new FileStream("king-james-bible.xlsm", FileMode.Create, FileAccess.Write, FileShare.None))
{
using (var stream = response.GetResponseStream())
{
stream.CopyTo(fs);
}
}
Could it be that the file your retrieving itself is corrupt?
Updated based on the new information
Okay the link is now working for me. Your problem is that the Excel file is sent using a gzip encoding. The code sample below works with your URL.
var request = WebRequest.CreateHttp("http://members.tsetmc.com/tsev2/excel/MarketWatchPlus.aspx?d=0");//"http://spreadsheetpage.com/downloads/xl/king-james-bible.xlsm");
var response = request.GetResponse();
string disposition = response.Headers["Content-Disposition"];
string filename = disposition.Substring(disposition.IndexOf("filename=") + 9).Replace("\"", "");
using (var fs = new FileStream(filename.Replace("/", "-"), FileMode.Create, FileAccess.Write, FileShare.None))
{
using (var stream = response.GetResponseStream())
{
using (GZipStream zipStream = new GZipStream(stream, CompressionMode.Decompress))
{
byte[] tempBytes = new byte[4096];
int i;
while ((i = zipStream.Read(tempBytes, 0, tempBytes.Length)) != 0)
{
fs.Write(tempBytes, 0, i);
}
}
}
}
I have used the info from this post for the gzip decoding: How do you download and extract a gzipped file with C#?