WebsiteSpark

Tuesday 31 January 2012

Listing FTP directory content using c# and .Net

Requirements:
Ø  Visual Studio 2010
Ø  A FTP site
What we are going to do here is to connect to a FTP site and list down the directory content in that FTP site. This uses FtpWebRequest class to connect and get response back from FTP site. The response stream is read using StreamReader class. The code and UI is as given below.





The UI consists of the following elements
Ø  Text box for URL, User ID & Password.
Ø  Multiline text box to display FTP response.
Ø  Command button to connect and get data from FTP location.
The code for command button click is given below, followed by the output UI.


using System;
using System.Linq;
using System.Windows.Forms;
using System.Net;
using System.IO;

namespace FTPWindow
{
    public partial class frmMain : Form
    {
        public frmMain()
        {
            InitializeComponent();
        }
       
        private void btnConnect_Click(object sender, EventArgs e)
        {
            FtpWebRequest ftpReq;
            string ftpURI = "ftp://" + txtServer.Text;
            ftpReq = (FtpWebRequest)FtpWebRequest.Create(ftpURI);
            ftpReq.Credentials = new NetworkCredential(txtUID.Text, txtPwd.Text);
            ftpReq.KeepAlive = true;
            ftpReq.UseBinary = true;
            ftpReq.Method = WebRequestMethods.Ftp.ListDirectory ;
           
            StreamReader reader =
                    new StreamReader(ftpReq.GetResponse().GetResponseStream());

            txtResp.Text = reader.ReadToEnd();
            //MessageBox.Show( (txtResp.Lines.Count() -1).ToString() + " item(s). " );
            reader.Close();
        }
    }
}






Enjoy!!!

1 comment:

  1. Jayan

    This is a great FTP Library for C#, it is reasonably priced too:
    https://www.kellermansoftware.com/p-39-net-ftp-library.aspx

    ReplyDelete