The example represents a C# .NET FTP client, which can log in to an FTP server, browse remote directories, download remote files, and upload local files to a selected FTP directory.
private void btnLogin_Click(object sender, System.EventArgs e)
{
ftp1.Port = Convert.ToInt32(edtPort.Text);
ftp1.Server = edtServer.Text;
ftp1.UserName = edtUser.Text;
ftp1.Password = edtPassword.Text;
ftp1.PassiveMode = cbPassiveMode.Checked;
ftp1.Open();
DoOpenDir(edtStartDir.Text);
}
private void DoOpenDir(string ADir)
{
string dir = ADir.TrimStart('/');
if (!StringUtils.IsEmpty(dir))
{
ftp1.ChangeCurrentDir(dir);
}
FillDirList();
}
private void FillDirList()
{
lbList.Items.Clear();
ftp1.GetDirectoryListing("");
edtStartDir.Text = ftp1.CurrentDir;
}
private void btnDownload_Click(object sender, System.EventArgs e)
{
if ((lbList.SelectedIndex > -1) &&
(lbList.Items[lbList.SelectedIndex].ToString() != "") &&
(lbList.Items[lbList.SelectedIndex].ToString()[0] != '/'))
{
saveFileDialog1.FileName = lbList.Items[lbList.SelectedIndex].ToString();
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
int size = (int)ftp1.GetFileSize(
lbList.Items[lbList.SelectedIndex].ToString());
using(FileStream dest = new FileStream(saveFileDialog1.FileName,
FileMode.Create))
{
ftp1.GetFile(lbList.Items[lbList.SelectedIndex].ToString(),
dest);
}
MessageBox.Show("Done");
}
}
}
private void btnUpload_Click(object sender, System.EventArgs e)
{
if(openFileDialog1.ShowDialog() == DialogResult.OK)
{
string fileName = Path.GetFileName(openFileDialog1.FileName);
FileInfo fileInf = new FileInfo(openFileDialog1.FileName);
using(FileStream source = new FileStream(openFileDialog1.FileName,
FileMode.Open, FileAccess.Read))
{
ftp1.PutFile(source, fileName);
}
MessageBox.Show("Done");
FillDirList();
}
}
The Ftp.DirectoryListing event is used for retrieving information about each file entry within the directory. A handler code for this event looks like the following.
private void ftp1_DirectoryListing(object sender,
CleverComponents.InetSuite.DirectoryListingEventArgs e)
{
string item = ((e.FileInfo.IsDirectory || e.FileInfo.IsLink) ? "/" : "")
+ e.FileInfo.FileName;
lbList.Items.Add(item);
}
Have questions?
Article ID: 144, Created: January 13, 2020 at 5:51 PM, Modified: April 6, 2020 at 1:55 PM