Joseph Caruso
Joseph Caruso

Reputation: 185

Download part of a file using HttpWebRequest without headers

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?

Upvotes: 0

Views: 827

Answers (1)

John Wu
John Wu

Reputation: 52290

The HTTP body of an image response is not a bytestream that you can use in an image viewer directly. Images are binary, while HTTP only allows for strings.

Instead, the HTTP body in this case is typically (depending on your content negotiation i.e. your accept/encoding headers) a Base64 string.

So change this

return result;

to this

return Convert.FromBase64String(result);

(and change your return type to byte[]).

If that doesn't work, visually inspect your request and response headers and check for compression such as gzip or deflate... see also this answer.

Upvotes: 2

Related Questions