Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Download the first 1000 bytes

Tags:

c#

.net

I need to download a text file from the internet using C#. The file size can be quite large and the information I need is always within the first 1000 bytes. Is this possible?

like image 371
Rana Avatar asked Oct 04 '10 07:10

Rana


2 Answers

Stolen from here.

string GetWebPageContent(string url)
{
    string result = string.Empty;
    HttpWebRequest request;
    const int bytesToGet = 1000;
    request = WebRequest.Create(url) as HttpWebRequest;

    //get first 1000 bytes
    request.AddRange(0, bytesToGet - 1);

    // the following code is alternative, you may implement the function after your needs
    using (WebResponse response = request.GetResponse())
    {
        using (Stream stream = response.GetResponseStream())
        {
            byte[] buffer = new byte[1024];
            int read = stream.Read(buffer, 0, 1000);
            Array.Resize(ref buffer, read);
            return Encoding.ASCII.GetString(buffer);
        }

    }
}

(Edited as requested in the comments... ;) )

like image 89
Marko Avatar answered Sep 23 '22 03:09

Marko


I did this as an answer to your newer question. You could put the range header in too if you want, but I excluded it.

    string GetWebPageContent(string url)
    {
        //string result = string.Empty;
        HttpWebRequest request;
        const int bytesToGet = 1000;
        request = WebRequest.Create(url) as HttpWebRequest;
        var buffer = new char[bytesToGet];
        using (WebResponse response = request.GetResponse())
        {
            using (StreamReader sr = new StreamReader(response.GetResponseStream()))
            {
                sr.Read(buffer, 0, bytesToGet);
            }
        }
        return new string(buffer);
    }
like image 2
Luke Schafer Avatar answered Sep 19 '22 03:09

Luke Schafer