I version 2 af .NET frameworket er der kommet understøttelse af FTP-protokollen. Ved hjælp af System.Net.WebClient kan man eksempelvis meget simpelt downloade filer som i følgende eksempel, hvor der hentes en lille tekstfil, der forklarer lidt om, hvad FTP (File Transfer Protocol) er for noget; men pas på at du ikke fordyber dig så meget i dokumentet, at du rammes af nostalgisk længsel efter Amigaer og VAX’er.
Dim request As New System.Net.WebClient()
request.Credentials = New System.Net.NetworkCredential("anonymous", "anders@and.dk")
Dim s As String = request.DownloadString("ftp://ftp.microsoft.com/developr/MSDN/FTP.TXT")
Dim writer As New System.IO.StreamWriter("C:\FTP.TXT")
writer.Write(s)
writer.Close()
System.Net.WebClient request = new System.Net.WebClient();
request.Credentials = new System.Net.NetworkCredential("anonymous", "anders@and.dk");
string s = request.DownloadString(@"ftp://ftp.microsoft.com/developr/MSDN/FTP.TXT");
System.IO.StreamWriter writer = new System.IO.StreamWriter(@"C:\FTP.TXT");
writer.Write(s);
writer.Close();
WebClient understøtter også asynkron up- og download som í følgende eksempel, hvor den samme fil hentes endnu en gang.
Private Sub btnStartDownload_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnStartDownload.Click
Dim request As New System.Net.WebClient()
request.Credentials = New System.Net.NetworkCredential("anonymous", "anders@and.dk")
request.DownloadStringAsync("ftp://ftp.microsoft.com/developr/MSDN/FTP.TXT")
AddHandler request.DownloadStringCompleted, AddressOf DownloadStringCompletedHandler
End Sub
Private Sub DownloadStringCompletedHandler(ByVal sender As Object, ByVal e As System.Net.DownloadStringCompletedEventArgs)
Dim s As String = e.Result
Dim writer As New System.IO.StreamWriter("C:\FTP.TXT")
writer.Write(s)
writer.Close()
End Sub
private void btnStartDownload_Click(object sender, EventArgs e)
{
System.Net.WebClient request = new System.Net.WebClient();
request.Credentials = new System.Net.NetworkCredential("anonymous", "anders@and.dk");
request.DownloadStringAsync(@"ftp://ftp.microsoft.com/developr/MSDN/FTP.TXT");
request.DownloadStringCompleted += DownloadStringCompletedHandler;
}
private void DownloadStringCompletedHandler(object sender, System.Net.DownloadStringCompletedEventArgs e)
{
string s = e.Result;
System.IO.StreamWriter writer = new System.IO.StreamWriter(@"C:\FTP.TXT");
writer.Write(s);
writer.Close();
}
Som et alternativ til System.Net.WebRequest kan man i
stedet benytte System.Net.FtpWebRequest-klassen ved hjælp af,
hvilken man udover up- og download også kan lave de andre
sædvanlige fil operationer: Directory-browsing, oprettelse og
sletning af directories, sletning af filer o.s.v.
|