FTP文件上传,下载,删除文件,检查文件(目录)存在,新建目录,获取文件夹下文件列表

public class FTPManage

    {

        private string userName = string.Empty;

        private string password = string.Empty;

        /// <summary>

        /// 待下载文件路径

        /// </summary>

        private string ftppath = string.Empty;

        private string url = null;

        private string filePath = null;//文件下载所存放位置

 

       /// <summary>

       /// 连接到ftp指定路径的目录

       /// </summary>

        /// <param name="ftpDirPath">ftp上文件存放或下载的路径</param>

       /// <param name="ftpUserID">ftp账号</param>

       /// <param name="ftpPassword">密码</param>

        public FTPManage(string ftpDirPath, string ftpUserID, string ftpPassword)

        {

            this.userName = ftpUserID;

            this.password = ftpPassword;

            this.ftppath = ftpDirPath;

        }

        /// <summary>

        /// 上传文件

        /// </summary>

        /// <param name="filePath">文件路径</param>

        /// <param name="fileName">文件名</param>

        /// <param name="parentFolderName">所在文件夹</param>

        /// <returns>上传是否成功</returns>

        public bool UploadFile(string filePath, string fileName, string parentFolderName)

        {

            bool result = false;

            try

            {

                if (!this.CheckDirectoryIsExists(parentFolderName))

                {

                    this.CreateDirectory(parentFolderName);

                }

                this.filePath = filePath;

                this.url = ftppath + "/" + parentFolderName + "/" + fileName;

 

                Thread objThread = new Thread(new ThreadStart(this.SubUploadFile));

                objThread.IsBackground = true;

                objThread.Start();

                objThread.Join();

 

                result = true;

            }

            catch (Exception objException)

            {

                throw objException;

            }

            return result;

        }

 

        /// <summary>

        /// 子上传文件

        /// </summary>

        private void SubUploadFile()

        {

            try

            {

                //创建ftp文件请求

                FtpWebRequest objFtpWebRequest = FtpWebRequest.Create(new Uri(this.url)) as FtpWebRequest;

 

                objFtpWebRequest.Credentials = new NetworkCredential(userName, password);

                objFtpWebRequest.KeepAlive = false;

                objFtpWebRequest.Method = WebRequestMethods.Ftp.UploadFile;

                objFtpWebRequest.UseBinary = true;

                objFtpWebRequest.KeepAlive = false;

                byte[] buffer = new byte[4096];

                int count = 0;

                //读取本地文件流

                using (FileStream objFileStream = new FileInfo(this.filePath).OpenRead())

                {

                    using (Stream objStream = objFtpWebRequest.GetRequestStream())

                    {

                        while ((count = objFileStream.Read(buffer, 0, buffer.Length)) > 0)

                        {

                            objStream.Write(buffer, 0, count);

                            objStream.Flush();

                        }

                        objFileStream.Close();

                        objStream.Close();

                    }

                }

            }

            catch (Exception objException)

            {

                throw objException;

            }

        }

 

        /// <summary>

        /// 下载文件

        /// </summary>

        /// <param name="filePath">文件路径</param>

        /// <param name="fileName">文件名</param>

        /// <param name="parentFolderName">所在文件夹</param>

        /// <returns>下载是否成功</returns>

        public bool DownloadFile(string filePath, string fileName, string parentFolderName)

        {

            bool result = false;

            try

            {

                if (this.CheckFileIsExists(fileName, parentFolderName))

                {

                    this.filePath = filePath;

                    this.url = ftppath + "/" + parentFolderName + "/" + fileName;

                    Thread objThread = new Thread(new ThreadStart(this.SubDownloadFile));

                    objThread.IsBackground = true;

                    objThread.Start();

                    objThread.Join();

                    result = true;

                }

                else

                {

                    throw new Exception("文件不存在,下载失败!");

                }

            }

            catch (Exception objException)

            {

                //throw objException;

            }

            return result;

        }

 

        /// <summary>

        /// 子下载文件

        /// </summary>

        private void SubDownloadFile()

        {

            try

            {

                FileStream objFileStream = new FileStream(this.filePath, FileMode.Create, FileAccess.Write, FileShare.None);

                BinaryWriter objBinaryWriter = new BinaryWriter(objFileStream);

                FtpWebRequest objFtpWebRequest = FtpWebRequest.Create(new Uri(this.url)) as FtpWebRequest;

                objFtpWebRequest.Credentials = new NetworkCredential(userName, password);

                objFtpWebRequest.KeepAlive = false;

                objFtpWebRequest.Method = WebRequestMethods.Ftp.DownloadFile;

                objFtpWebRequest.UseBinary = true;

 

                byte[] buffer = new byte[4096];

                int count = 0;

                using (Stream objStream = objFtpWebRequest.GetResponse().GetResponseStream())

                {

                    while ((count = objStream.Read(buffer, 0, buffer.Length)) > 0)

                    {

                        objBinaryWriter.Write(buffer, 0, count);

                        objBinaryWriter.Flush();

                    }

                    objBinaryWriter.Close();

                    objFileStream.Close();

                    objStream.Close();

                }

            }

            catch

            {

                throw;

            }

        }

 

        /// <summary>

        /// 删除文件

        /// </summary>

        /// <param name="fileName">文件名</param>

        /// <param name="parentFolderName">所在文件夹</param>

        /// <returns>删除是否成功</returns>

        public bool DeleteFile(string fileName, string parentFolderName)

        {

            bool result = false;

            try

            {

                if (this.CheckFileIsExists(fileName, parentFolderName))

                {

                    this.url = ftppath + "/" + parentFolderName + "/" + fileName;

                    FtpWebRequest objFWR = FtpWebRequest.Create(new Uri(this.url)) as FtpWebRequest;

                    objFWR.Credentials = new NetworkCredential(userName, password);

                    objFWR.KeepAlive = false;

                    objFWR.Method = WebRequestMethods.Ftp.DeleteFile;

                    objFWR.UseBinary = true;

objFWR.GetResponse().GetResponseStream().Close();

                    result = true;

                }

                else

                {

                    result = false;

                }

            }

            catch (Exception objException)

            {

                throw objException;

            }

            return result;

        }

 

        /// <summary>

        /// 删除文件夹

        /// </summary>

        /// <param name="fileName">文件名</param>

        /// <param name="parentFolderName">所在文件夹</param>

        /// <returns>删除是否成功</returns>

        public bool DeleteDirectory(string folderName)

        {

            bool result = false;

            try

            {

                if (this.CheckDirectoryIsExists(folderName))

                {

                    this.url = ftppath + "/" + folderName;

                    FtpWebRequest objFWR = FtpWebRequest.Create(new Uri(this.url)) as FtpWebRequest;

 

                    objFWR.Credentials = new NetworkCredential(userName, password);

                    //objFWR.KeepAlive = false;

                    objFWR.Method = WebRequestMethods.Ftp.RemoveDirectory;

                    //objFWR.UseBinary = true;

                    objFWR.GetResponse().Close();

                    result = true;

                }

                else

                {

                    result = false;

                }

            }

            catch (Exception objException)

            {

                throw objException;

            }

            return result;

        }

 

 

        /// <summary>

        /// 检查文件是否存在

        /// </summary>

        /// <param name="fileName">文件名</param>

        /// <param name="parentFolderName">所在文件夹</param>

        /// <returns>是否存在</returns>

        public bool CheckFileIsExists(string fileName, string parentFolderName)

        {

            bool result = false;

            try

            {

                StringBuilder objSB = new StringBuilder();

                FtpWebRequest objFWR = FtpWebRequest.Create(new Uri(ftppath + "/" + parentFolderName + "/")) as FtpWebRequest;

 

                objFWR.UseBinary = true;

                objFWR.Credentials = new NetworkCredential(userName, password);

                objFWR.KeepAlive = false;

                objFWR.Method = WebRequestMethods.Ftp.ListDirectory;

                using (WebResponse objWebResponse = objFWR.GetResponse())

                {

                    using (StreamReader objSR = new StreamReader(objWebResponse.GetResponseStream()))

                    {

                        string line = objSR.ReadLine();

                        while (!String.IsNullOrEmpty(line))

                        {

                            objSB.Append(line);

                            objSB.Append("\n");

                            line = objSR.ReadLine();

                        }

                        objSR.Close();

                        objWebResponse.Close();

                    }

                }

                if (objSB.ToString().Contains(fileName))

                {

                    result = true;

                }

            }

            catch (Exception objException)

            {

                throw objException;

            }

            return result;

        }

 

        /// <summary>

        /// 检查目录是否存在

        /// </summary>

        /// <param name="parentFolderName">目录名称</param>

        /// <returns>目录是否存在</returns>

        public bool CheckDirectoryIsExists(string parentFolderName)

        {

            bool result = false;

            try

            {

                Regex regexName = new Regex(@"[^\s]*$", RegexOptions.Compiled);

                FtpWebRequest objFWR = FtpWebRequest.Create(new Uri(ftppath + "/")) as FtpWebRequest;

                objFWR.UseBinary = true;

                objFWR.Credentials = new NetworkCredential(userName, password);

                objFWR.KeepAlive = false;

                objFWR.Method = WebRequestMethods.Ftp.ListDirectoryDetails;

                using (Stream objStream = objFWR.GetResponse().GetResponseStream())

                {

                    using (StreamReader objSR = new StreamReader(objStream))

                    {

                        string line = objSR.ReadLine();

                        while (!String.IsNullOrEmpty(line))

                        {

                            GroupCollection objGC = regexName.Match(line).Groups;

 

                            if (objGC.Count.Equals(1))

                            {

                                string path = objGC[0].Value.Trim();

 

                                if (path.Equals(parentFolderName))

                                {

                                    result = true;

                                    break;

                                }

                                else

                                {

                                    line = objSR.ReadLine();

                                }

                            }

                        }

                    }

                }

            }

            catch (Exception objException)

            {

                throw objException;

            }

            return result;

        }

 

        /// <summary>

        /// 创建目录

        /// </summary>

        /// <param name="parentFolderName">目录名称</param>

        /// <returns>创建是否成功</returns>

        public bool CreateDirectory(string parentFolderName)

        {

            bool result = false;

            try

            {

                FtpWebRequest objFWR = FtpWebRequest.Create(new Uri(ftppath + "/" + parentFolderName + "/")) as FtpWebRequest;

 

                objFWR.UseBinary = true;

                objFWR.Credentials = new NetworkCredential(userName, password);

                objFWR.KeepAlive = false;

                objFWR.Method = WebRequestMethods.Ftp.MakeDirectory;

                objFWR.GetResponse().GetResponseStream().Close();

                result = true;

            }

            catch (Exception objException)

            {

                throw objException;

            }

            return result;

        }

 

        /// <summary>

        /// 获取Ftp服务器上指定目录下的所有文件和文件夹

        /// </summary>

        /// <returns></returns>

        public string[] GetFileList(string parentFolderName)

        {

            string[] downloadFiles;

            StringBuilder result = new StringBuilder();

            FtpWebRequest reqFTP;

            try

            {

                reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftppath + "/" + parentFolderName + "/"));

                reqFTP.UseBinary = true;

                reqFTP.Credentials = new NetworkCredential(userName, password);

                reqFTP.Method = WebRequestMethods.Ftp.ListDirectory;

                reqFTP.KeepAlive = false;

                WebResponse response = reqFTP.GetResponse();

                StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding("GB2312"));

                string line = reader.ReadLine();

                while (line != null)

                {

                    result.Append(line);

                    result.Append("\n");

                    line = reader.ReadLine();

                }

                result.Remove(result.ToString().LastIndexOf('\n'), 1);

                reader.Close();

                response.Close();

                return result.ToString().Split('\n');

            }

            catch (Exception ex)

            {

                downloadFiles = null;

                return downloadFiles;

            }

        }

    }

 

 

posted @ 2013-05-22 17:31  LannyLiu  阅读(415)  评论(0编辑  收藏  举报