(C#) Download text or bytes via HTTP

Downloads contents as a byte array or string, depending on need.

  1. namespace VK.Snippets
  2. {
  3.     using System.Collections.Generic;
  4.     using System.IO;
  5.     using System.Net;
  6.     using System.Text;
  7.  
  8.     public static class HttpFetcher
  9.     {
  10.         public static string FetchPage(string url, string username = "", string password = "", string domain = "")
  11.         {
  12.             string page = Encoding.ASCII.GetString(FetchContent(url, username, password, domain));
  13.  
  14.             return page;
  15.         }
  16.  
  17.         public static byte[] FetchContent(string url, string username = "", string password = "", string domain = "")
  18.         {
  19.             List<byte> contentBytes = new List<byte>();
  20.  
  21.             HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
  22.             if (username != "" && password != "" && domain != "")
  23.             {
  24.                 request.Credentials = new NetworkCredential(username, password, domain);
  25.             }
  26.  
  27.             HttpWebResponse response = (HttpWebResponse)request.GetResponse();
  28.             if (response.StatusCode == HttpStatusCode.OK)
  29.             {
  30.                 Stream responseStream = response.GetResponseStream();
  31.                
  32.                 int b;
  33.                 while ((b = responseStream.ReadByte()) != -1)
  34.                 {
  35.                     contentBytes.Add((byte)b);
  36.                 }
  37.             }
  38.  
  39.             return contentBytes.ToArray();
  40.         }
  41.     }
  42. }
This entry was posted in C# and tagged , , , , , , , , , , . Bookmark the permalink. Trackbacks are closed, but you can post a comment.

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Why ask?