Friday, December 10, 2010

How to get list of file and directory names from remote direcotry

Many of times we requires to get list of all name of files and folder which exists on remote server.

To get list of File and Folder names from Remote Directory / Remote Server

public void getDirList()
        {
            FtpWebRequest _lsDirFtp;

            _lsDirFtp = (FtpWebRequest)FtpWebRequest.Create("ftp://myFTPIPorName//MyDirecoty/");
            _lsDirFtp.KeepAlive = false;
            _lsDirFtp.Credentials = new NetworkCredential("username", "password");

            _lsDirFtp.Method = WebRequestMethods.Ftp.ListDirectoryDetails;



            WebResponse response = _lsDirFtp.GetResponse();
            
            StreamReader reader = new StreamReader(response.GetResponseStream());



            //Get Directory/File names

            FtpWebRequest _lsDirDetailsFtp;
            _lsDirDetailsFtp = (FtpWebRequest)FtpWebRequest.Create("ftp://myFTPIPorName//MyDirecoty/");
            _lsDirDetailsFtp.KeepAlive = false;

            _lsDirDetailsFtp.Credentials = new NetworkCredential("username", "password");

            _lsDirDetailsFtp.Method = WebRequestMethods.Ftp.ListDirectory;



            WebResponse response2 = _lsDirDetailsFtp.GetResponse();

            StreamReader reader2 = new StreamReader(response2.GetResponseStream());



            //read file/directory names into arraylist

            string lsdirectory = reader2.ReadLine();

            ArrayList lsnames = new ArrayList();

            while (lsdirectory != null)
            {

                lsnames.Add(lsdirectory);
                Response.Write("fileName:" + lsdirectory);

                lsdirectory = reader2.ReadLine();

            }



            //read through directory details response

            string line = reader.ReadLine();

            while (line != null)
            {

                //if (line.StartsWith("d") && !line.EndsWith(".")) //"d" = dir don't need "." or ".." dirs
                //{

                    foreach (String chk in lsnames) //compare basic dir output to detail dir output to get dir name
                    {

                        if (line.EndsWith(chk))
                        {

                            //found dir
                          Response.Write ("fileName:" + chk);

                            // Console.WriteLine(chk);

                        }

                    }

               // }

                line = reader.ReadLine();

            }


        }

Solution By:

Rajesh Rolen

Share This!


No comments:

Powered By Blogger · Designed By Seo Blogger Templates