Sample C# and VB code to download a file

  • From: Jamal Mazrui <empower@xxxxxxxxx>
  • To: programmingblind@xxxxxxxxxxxxx
  • Date: Wed, 14 Jan 2009 14:37:37 -0500 (EST)

From the archive
http://EmpowermentZone.com/url2file.zip

Based on recent discussion, I thought this sample program may be of
interest.  It downloads a user-specified file from the Internet, via HTTP,
FTP, or another common protocol.  It is built with the C# and Visual Basic
command-line compilers, which are part of  the .NET Framework 2.0 SDK.
There are source code and batch files for compiling the program with
either language.

The program, url2file.exe, is a console-mode executable that takes two
parameters, specifying an Internet URL to download and the resulting file
on disk.  Enclose the file path in quotes if it contains a space
character.

Differences between the C# and VB versions are mostly syntax except for a
couple of points.  The VB version uses the My namespace, which contains a
shared method to download a file.  That namespace is not available to C#,
so it instantiates a Network object before calling the method.  The C#
batch file also has to reference the Microsoft.VisualBasic.dll assembly
containing this functionality, whereas VB references it by default.

I am also pasting the source code of both versions in this email message
below.

Jamal

[Start of url2file.cs]

using Microsoft.VisualBasic.Devices;
using System;
using System.IO;

class Program {
static void Main(string[] aArgs) {
if (aArgs.Length < 2) {
Console.WriteLine("Syntax:\nurl2file.exe UrlPath FilePath");
return;
}

Console.WriteLine("Downloading");
string sUrl = aArgs[0];
string sFile = aArgs[1];
if (File.Exists(sFile)) File.Delete(sFile);
Network net = new Network();
net.DownloadFile(sUrl, sFile);

if (File.Exists(sFile))  Console.WriteLine("Done!");
else Console.WriteLine("Error!");
}
}

[End of url2file.cs]

[Start of url2file.vb]
Imports System
Imports System.IO

Class Program
Shared Sub Main(aArgs As String())
If (aArgs.Length < 2) Then
Console.WriteLine("Syntax:" + vbLf + "Url2file.exe UrlPath FilePath")
Return
End If

Console.WriteLine("Downloading")
Dim sUrl As String = aArgs(0)
Dim sFile As String = aArgs(1)
If File.Exists(sFile) Then File.Delete(sFile)
My.Computer.Network.DownloadFile(sUrl, sFile)

If File.Exists(sFile) Then
Console.WriteLine("Done!")
Else
Console.WriteLine("Error!")
End If
End Sub
End Class

[End of url2file.vb]

__________
View the list's information and change your settings at 
//www.freelists.org/list/programmingblind

Other related posts: