How to implement simple wget in C#

.NET is such a good programming environment because it provides many useful standard libraries. Actually, this concept is very similar to battery included in Python. The best part of .NET is that we have Mono so it is possible to develop .NET application on Linux to run on Windows. I have been asked to find a solution for retrieving content from specified URL using HTTP protocol in C#. Here is the code.

I use WebClient() in System.Net.

wget.cs

using System;
using System.Net;
using System.Text;
 
class CSharpHttpClient {
 
    string Get(string url) {
        WebClient c = new WebClient();
        byte[] response = c.DownloadData(url);
        return Encoding.ASCII.GetString(response);
    }
 
    static void Main(string[] args) {
        CSharpHttpClient c = new CSharpHttpClient();
        if (args.Length != 1) {
            Console.WriteLine("usage: wget.exe url");
            System.Environment.Exit(-1);
        }
        Console.Write(c.Get(args[0]));
    }
}

To compile above code, I use mcs and Makefile as follows.

Makefile

TARGET=wget.exe
MCS=mcs
 
all: $(TARGET)
 
clean:
        rm -f $(TARGET)
 
%.exe: %.cs
        $(MCS) $(MCSFLAGS) $(LIBS) -out:$@ $<

Simply build wget.exe by running make. wget.exe needs a URL in the first argument, e.g.,

wget.exe http://www.google.com/

Tags: , ,

I am trying to download

I am trying to download content where the site is password protected (I basically need to sign in before I can see any content). How could I download such content? Also, if I have a cookie file, is it possible to attach the cookie file with the Webclient liket WebRequest object? Thanks.

Post new comment