I am trying to send a file from my machine to the browser, so that it can be downloaded, in a .NET application I am working on. I am using the code in the this SO answer, but instead of using an HttpWebRequest I am using a FileWebRequest because I am accessing the file on my local machine. The request looks like this:
FileWebRequest fileReq = (FileWebRequest)WebRequest.Create(@"file:///C:/Tmp/new.html");
and when I copy the url file:///C:/Tmp/new.html
into the browser, it gives me the correct file. But when I use fileReq.ContentLength
in my code it always returns 0
, which leads me to believe that the file is not being read for some reason. Can anyone tell me what's going on here?
EDIT: Here's my code, like I said exactly like from the other SO question, but I used FileWebRequest instead of HttpWebRequest.
Stream stream = null;
int bytesToRead = 10000;
byte[] buffer = new Byte[bytesToRead];
try
{
FileWebRequest fileReq = (FileWebRequest)WebRequest.Create(@"file:///C:/Tmp/new.html");
FileWebResponse fileResp = (FileWebResponse)fileReq.GetResponse();
if (fileReq.ContentLength > 0)
{
fileResp.ContentLength = fileReq.ContentLength;
stream = fileResp.GetResponseStream();
var resp = HttpContext.Current.Response;
resp.ContentType = "application/octet-stream";
resp.AddHeader("Content-dsiposition", "attachment; filename=" + url);
resp.AddHeader("Content-Length", fileResp.ContentLength.ToString());
int length;
do
{
if (resp.IsClientConnected)
{
length = stream.Read(buffer, 0, bytesToRead);
resp.OutputStream.Write(buffer, 0, length);
resp.Flush();
buffer = new Byte[bytesToRead];
}
else
{
length = -1;
}
} while (length > 0);
}
}
catch (Exception ex)
{
FileLabel.Text = ex.Message.ToString();
}
finally
{
if (stream != null)
{
stream.Close();
}
}