Comment Télécharger un fichier avec un utilitaire en ligne de commande en c# .net 2.0

(Mise à jour du 14/01/2007) 

J'avais besoin pour un un developpement de telecharger un fichier a heure régulière, n'ayant pas trouvé ce que je voulais pour réaliser cette opération, j'ai ecrit ce petit utilitaire :

 

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Net;

namespace HttpDownload
{
class Program
{
static void Main(string[] args)
{
string url = null;
string fileName = null ;
string user = null;
string password = null;

if (args.Length == 2)
{
url = args[0];
fileName = args[1];
}
else if (args.Length == 4)
{
url = args[0];
fileName = args[1];
user = args[2];
password = args[3];
}
else
{
Console.WriteLine("for using this tool :\r\n");
Console.WriteLine();
Console.WriteLine("HttpDownload <url> <destinationFileName>");
Console.WriteLine("or");
Console.WriteLine("HttpDownload <url> <destinationPath>");
Console.WriteLine("or with NTLM authentication");
Console.WriteLine("HttpDownload <url> <destinationFileName> <user> <password>");
Console.WriteLine("or");
Console.WriteLine("HttpDownload <url> <destinationPath> <user> <password>");
Console.WriteLine();
Console.WriteLine("Example :");
Console.WriteLine(@"HttpDownload http://www.microsoft.com/file.zip c:\temp\file.zip");
Console.WriteLine(@"HttpDownload http://www.microsoft.com/file.zip c:\temp");
return;
}

try
{
// Is folder or not ?
if (System.IO.Directory.Exists(fileName))
{
Uri u = new Uri(url);
string[] token = u.LocalPath.Split('/');
if (token.Length > 0)
{
fileName = System.IO.Path.Combine(fileName, token[token.Length - 1]);
}
else
{
fileName = System.IO.Path.Combine(fileName, u.LocalPath);
}
}

using (System.IO.FileStream fs = new System.IO.FileStream(fileName, System.IO.FileMode.Create, System.IO.FileAccess.Write, System.IO.FileShare.Write))
{
CrawlFile(url, fs, user, password);
fs.Flush();
fs.Close();
}
}
catch (Exception ex)
{
Console.WriteLine("Error : " + ex.ToString());
}
}

/// <summary>
/// Gets the content of the specified webpage.
/// </summary>
/// <param name="url">The url to get.</param>
/// <param name="output">The output.</param>
/// <returns></returns>
public static void CrawlFile(string url, Stream output, string user, string password)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
// request.Timeout = Properties.Settings.Default.ConfigSection.HttpTimeout;
request.Method = "GET";
request.KeepAlive = true;
request.Accept = @"*/*";

if (string.IsNullOrEmpty(user) == false && string.IsNullOrEmpty(password) == false)
{
NetworkCredential credential = new NetworkCredential(user, password);
CredentialCache credentialCache = new CredentialCache();
credentialCache.Add(new Uri(url), "NTLM", credential);
request.Credentials = credentialCache;
}

HttpWebResponse response = null;
try
{
response = (HttpWebResponse)request.GetResponse();
}
catch
{
if (response != null)
{
response.Close();
response = null;
}
request = null;
throw;
}

if (response.StatusCode != HttpStatusCode.OK)
{
throw new WebException(string.Format("Status code: {0}", response.StatusCode));
}

using (Stream str = response.GetResponseStream())
{
long contentLenght = response.ContentLength;
Console.WriteLine("Download in progress for : {0}", System.IO.Path.GetFileName(response.ResponseUri.PathAndQuery));
Console.WriteLine("Size : {0:f2} Mb", contentLenght / 1000000.0);
int bufferSize = 1024;
long old = 0;
byte[] buffer = new byte[bufferSize];
int pos = 0;
System.Threading.ThreadPool.RegisterWaitForSingleObject(
new System.Threading.AutoResetEvent(false)
, new System.Threading.WaitOrTimerCallback(delegate(object state, bool timedOut)
{
Console.WriteLine("Downloaded : {0:f2}Mb > {1}kb/s > {2:p}", output.Length / 1000000.0, (output.Length - old) / bufferSize, output.Length / (contentLenght * 1.0));
old = output.Length;
})
, null
, 1000
, false);
while ((pos = str.Read(buffer, 0, bufferSize)) > 0)
{
output.Write(buffer, 0, pos);
}
str.Close();
}

if (response != null)
{
response.Close();
response = null;
}
request = null;
}
}
}
Il y a maintenant la possibilité de télécharger un fichier avec une autentification NTLM et affichage d'un indicateur de progression un peu plus sexy.
Merci John pour la partie NTLM ;)

del.icio.us tags: , , ,

Aucun commentaire: