dx tdas
dx tdas

Reputation: 41

How can I download file line by line in .NET core?

I have tried to use HttpWebResponse.GetResponse(); but that is not a part of .NET core, and I couldn't figure out anything else.

I only have this so far, but this downloads the whole file

string first_line(string url)
{
    var httpClient = new HttpClient();
    httpClient.DefaultRequestHeaders.UserAgent.Add(new ProductInfoHeaderValue("MyClient", "1.0"));
    var otp = httpClient.GetStringAsync(url);

    return imaginary_first_line;
}

I would like to download only the first line without the rest of the file.

Upvotes: 3

Views: 2690

Answers (1)

Michał Komorowski
Michał Komorowski

Reputation: 6238

The solution is to use Range header. It says a server that we are interested only in the part of a file. Here is an example in which only 50 bytes are downloaded:

using (var client = new HttpClient())
{
   var request = new HttpRequestMessage(HttpMethod.Get, url);
   //Let's read only 50 bytes
   request.Headers.Range = new RangeHeaderValue(0, 50);

   using (var response = await client.SendAsync(request))
      using (var stream= await response.Content.ReadAsStreamAsync())
      {
         //The buffer can store 1000 bytes but only 50 will be send from the server
         var buffer = new byte[1000];
         stream.Read(buffer, 0, 1000);
         //...
      }
}

You can use Fiddler to check that the server really returns only 50 bytes.

You can also use HttpWebRequest class in the following way:

var request = (HttpWebRequest)WebRequest.Create(url);
request.Headers[HttpRequestHeader.Range] = "bytes=0-50";

var response = await request.GetResponseAsync();
//...

The result should be the same.

Upvotes: 3

Related Questions