Wednesday, August 14, 2013

Get file names from FTP site

this example is how to get list of file names on specific ftp site and bind the result to RadListView with two column.
I used RadListView of Telerik. You can use standard  ListView or ASP.

public void ListDirectory()
        {
            var request = createRequest(URL, WebRequestMethods.Ftp.ListDirectory);

            DataTable DT = new DataTable();
            DataColumn col1 = new DataColumn("URL");
            DataColumn col2 = new DataColumn("FILENAME");
            DT.Columns.Add(col1);
            DT.Columns.Add(col2);
            DT.Rows.Clear();

            using (var response = (FtpWebResponse)request.GetResponse())
            {
                using (var stream = response.GetResponseStream())
                {
                    using (var reader = new StreamReader(stream, true))
                    {
                        while (!reader.EndOfStream)
                        {
                            string line = reader.ReadLine();
                            DT.Rows.Add(URL + line, line);
                        }
                    }
                }
            }

            this.listView.DataSource = DT;
        }
private FtpWebRequest createRequest(string uri, string method)
        {
            var r = (FtpWebRequest)WebRequest.Create(uri);

            r.Credentials = new NetworkCredential(USERNAME, PASSWORD);
            r.Method = method;

            return r;
        }

0 comments: