viernes, 10 de julio de 2009

How to download a file using C# (Descargar un archivo usando C#)

Probably the easiest way to download a file from net using c# programming language is through the WebClient class. In the following code snippet we can see how it is done.


using System;
using System.Net;
using System.IO;

namespace Web
{
public static class Web
{
public static int Main(string[] args)
{
if( args.Length < 2 )
{
Console.WriteLine("FileGet v.0.1 - Download a file from the net.");
Console.WriteLine("www.manuelvillasur.com");
Console.WriteLine("");
Console.WriteLine("Usage:");
Console.WriteLine(" FILEGET url_of_file file_on_disk");
Console.WriteLine("");
return 1;
}

Console.WriteLine("I going to try download the file {0} from {1}", args[1], args[0]);

try
{
WebClient wc = new WebClient();
wc.DownloadFile(args[0], args[1]);
Console.WriteLine("The file has been downloaded.");
return 0;
}
catch(Exception)
{
Console.WriteLine("Hasn't been possible to download de file");
Console.WriteLine("May be your firewall locked my!");
Console.WriteLine("May be the file hasn't been founded");
return -1;
}
}
}
}

No hay comentarios:

Publicar un comentario