string URI = "ftp://mirror.x10.com/gnuftp/gnu/README.DESCRIPTIONS";
System.IO.FileInfo fi = new System.IO.FileInfo(@"c:\temp\deleteme.txt");
System.Net.FtpWebRequest ftp =
(System.Net.FtpWebRequest)System.Net.FtpWebRequest.Create(URI);
ftp.Credentials = new System.Net.NetworkCredential("anonymous", "");
ftp.KeepAlive = false;
ftp.Method = System.Net.WebRequestMethods.Ftp.DownloadFile;
ftp.UseBinary = true;
using (System.Net.FtpWebResponse response = (System.Net.FtpWebResponse)ftp.GetResponse())
{
using (System.IO.Stream responseStream = response.GetResponseStream())
{
using (System.IO.FileStream fs = fi.OpenWrite())
{
try
{
byte[] buffer = new byte[2048];
int read = 0;
do
{
read = responseStream.Read(buffer, 0, buffer.Length);
fs.Write(buffer, 0, read);
} while (!(read == 0));
responseStream.Close();
fs.Flush();
fs.Close();
}
catch (Exception)
{
fs.Close();
fi.Delete();
throw;
}
}
responseStream.Close();
}
response.Close();
}
It almost makes more sense to shell out to c:\windows\system32\ftp.exe as in this VBA code.
Dim ff As Integer
ff = FreeFile
ff = FreeFile
Open "c:\temp\ftpcommands.scr" For Output As #ff
Print #ff, "open mirror.x10.com"
Print #ff, "anonymous"
Print #ff, "no_password"
Print #ff, "cd gnuftp/gnu"
Print #ff, "binary"
Print #ff, "get README.DESCRIPTIONS c:\temp\deleteme3.txt"
Print #ff, "bye"
Close #ff
ff = FreeFile
Open "c:\temp\ftpcommands.bat" For Output As #ff
Print #ff, "ftp -s:c:\temp\ftpcommands.scr"
Print #ff, "Echo ""Complete"" > c:\temp\ftpcommands.done"
Close #ff
Shell "c:\temp\ftpcommands.bat", vbHide
Do While Dir("c:\temp\ftpcommands.done") = ""
DoEvents
Loop
Dim dtmContinueAt As Date
dtmContinueAt = Now + TimeValue("0:00:03")
Do While Now < dtmContinueAt
Loop
Kill "c:\temp\ftpcommands.scr"
Kill "c:\temp\ftpcommands.bat"
Kill "c:\temp\ftpcommands.done"
Now contemplate this equivalent Ruby code.
require 'net/ftp'
Net::FTP.open('mirror.x10.com') do |ftp|
ftp.login
files = ftp.chdir('gnuftp/gnu')
ftp.getbinaryfile('README.DESCRIPTIONS', 'c:\temp\deleteme2.txt')
end
I feel prompted to ask, just wtf does Microsoft have against FTP? Aside from that, the obvious question is “will .NET 3.x ‘Orcas’ do better?” Or maybe the obvious question is, “is .NET a misnomer*?”
* Because last time I checked FTP was an Internet protocol: “a system for transferring computer files especially via the Internet.”