I'm trying to download a portion of a file in C# using an HttpWebRequest
, and am doing so successfully, but only to some degree. While my method works fine with text-based files (eg. .txt
, .php
, .html
, etc.) it doesn't seem to play friendly with other things such as .jpg
, .png
, etc. which is a problem, because it should download just fine regardless of the file-type (It's just a download, not something to open the file, so file-type is irrelevant).
The problem is, while downloading text-based files properly, it doesn't play so nicely with other file-types. For example, I tried using the method for a .jpg
, and it had extra data at the beginning of the file (Possibly HTTP response header?) and was roughly 200 KB larger than the actual file-size.
I'm using the following method to download the files (I've set the URLto the correct URL (Yes, I have octuple checked, it is the correct URL.), and I've set threads to 1 (thus downloading the entire file) which works for text-based files but not other file-types):
public static string DownloadSector(string fileurl, int sector)
{
string result = string.Empty;
HttpWebRequest request;
request = WebRequest.Create(fileurl) as HttpWebRequest;
//get first 1000 bytes
request.AddRange(sectorSize*sector, ((sector + 1) * sectorSize) - 1);
//request.
Console.WriteLine("Range: " + (sectorSize * sector) + " - " + (((sector + 1) * sectorSize) - 1));
// the following code is alternative, you may implement the function after your needs
using (WebResponse response = request.GetResponse())
{
Console.WriteLine("Content length:\t" + response.ContentLength);
Console.WriteLine("Content type:\t" + response.ContentType);
using (StreamReader sr = new StreamReader(response.GetResponseStream()))
{
result = sr.ReadToEnd();
}
}
return result;
}
So, any idea what the problem is and how to fix this?