I've used this example to create a very simple FTP client which purpose is just to download all files from an FTP server and after succeded download, delete this files from the server.
public static bool DisplayFileFromServer(Uri serverUri)
{
// The serverUri parameter should start with the ftp:// scheme.
if (serverUri.Scheme != Uri.UriSchemeFtp)
{
return false;
}
// Get the object used to communicate with the server.
WebClient request = new WebClient();
// This example assumes the FTP site uses anonymous logon.
request.Credentials = new NetworkCredential ("anonymous","[email protected]");
try
{
byte [] newFileData = request.DownloadData (serverUri.ToString());
string fileString = System.Text.Encoding.UTF8.GetString(newFileData);
Console.WriteLine(fileString);
}
catch (WebException e)
{
Console.WriteLine(e.ToString());
}
return true;
}
I've implemeted the multiple files download such as first getting the files to be downloaded into a List
I've added the
foreach (string file in fileList)
before the try { byte[] ... section byt this creates a new connection to the ftp server for each file.
Does anyone know how to create this multiple file download so that the established connection is reused for each file so that there will just be one used connection to the ftp server?
Is there possible to change the current uri string in an established connection?
I would be glad for any suggestions how to perform this tiny ftp client.
/Daysim
Simon DahlquistPosted Apr 21, 2010, 11:34 AM
I think I'll focus on getting the single thread approach before I add multithreading.
I've found some stuff about the KeepAlive property that I will use in my code and see if that'll force the program to reuse the connection.
Augustin JianuPosted Apr 21, 2010, 7:15 AM
Simon DahlquistPosted Apr 7, 2010, 1:54 AM
public void GetFilesFromFTP()
{
fileList = new List<string>(GetFileList());
//The serverUri needs to start with ftp://
WebClient request = new WebClient();
request.Credentials = new NetworkCredential(ftpUserID,
ftpPassword);
foreach (string file in fileList)
{
try
{
Uri serverUri = new Uri(path + file);
byte[] newFileData = request.DownloadData(serverUri.ToString());
FileStream localFile = new FileStream(serverUri.LocalPath, FileMode.Create);
localFile.Write(newFileData, 0, newFileData.Length);
localFile.Close();
label1.Text = "File saved: " + file;
label1.Refresh();
}
catch (Exception ex)
{
error = true;
MessageBox.Show(ex.Message);
break;
}
}
request.Dispose();
}
The getFileList() function is my own as well if someone wounder.
The problem with this code is that request.DownloadData(serverUri.ToString()) creates a new socket connection to se FTP server for each
file and do not reuse the connection already established. Does someone know how to achieve reuse of the connection?
I've tried to google on this but all tutorials, examples and so on only describe single file download.
Sam HobbsPosted Apr 6, 2010, 10:27 PM