Got something to write about? Check out our Article Builder.
Dowload Files in C#
by Randy Charles Morin

This is the fifth article in a series on Internet Programming with C#. The first four articles addressed Internet Protocols; SMTP, POP3 and NNTP. The fourth address port scanning in C#. This article will address how to download files over the Internet with C#.

What exactly do I mean by download a file over the Internet? Neither the Internet protocol nor its popular TCP/IP (Transmission Control Protocol) transport directly support file downloads. File transfer over the Internet usually occur over FTP (File Transfer Protocol) or HTTP (HyperText Transfer Protocol). C# provides for downloading files using both of these protocols.

The more I've gotten to use C# and the dotNET library, the more I am impressed. In this case, the dotNET library has a class called WebClient that has a method DownloadFile. The method will download pretty much any file from a URI. This includes but is not limited to the three popular URI protocols; http and file. Unfortunately, the method doesn't seem to work for the ftp protocol.

Sample code to write a small download utility follows.

Listing 1: DownloadFile
static void Main(string[] args)
{
    if (args.Length < 2)
    {
        Console.WriteLine
          ("Usage: downloadfile [url] [localfile]");
        return;
    }
    try
    {
        System.Net.WebClient client =
          new WebClient();
        client.DownloadFile(args[0], args[1]);
    }
    catch(Exception e)
    {
        Console.WriteLine(e.ToString());
    };
}


That's just too simple, but then, that's the beauty of Microsoft's new C# and dotNET framework. Congratulations to the Microsoft team.

About the Author
Randy Charles Morin lives with his wife, Bernadette and two kids, Adelaine and Brayden in Brampton, Canada. He is the author of the KBCafe.com website, many programming books and many articles.

Copyright 2002-2003 Randy Charles Morin



 

Other Views

corner
Popular resources and forums for programmers on Programmersheaven.com
Assembly, Basic, C, C#, C++, Delphi, Java, JavaScript, Pascal, Perl, PHP, Python, Ruby, Visual Basic
© Copyright 2009 Programmersheaven.com - All rights reserved.
Reproduction in whole or in part, in any form or medium without express written permission is prohibited.
Violators of this policy may be subject to legal action. Please read our Terms Of Use and Privacy Statement for more information.
Publisher: Lars Hagelin. Read the latest words from the publisher here.
Be the first to sign up for Lars Hagelin’s In-depth Outsourcing Newsletter here.
bootstrapLabs Logo A bootstrapLabs project.