注册 登录  
 加关注
   显示下一条  |  关闭
温馨提示!由于新浪微博认证机制调整,您的新浪微博帐号绑定已过期,请重新绑定!立即重新绑定新浪微博》  |  关闭

淡忘邻人

二十七,始发愤

 
 
 

日志

 
 
 
 

获取FTP文件目录类 C#  

2010-05-29 21:21:58|  分类: C# |  标签: |举报 |字号 订阅

  下载LOFTER 我的照片书  |

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.IO;
    using System.Net;
    using System.Diagnostics;


    public class FTPFactory
    {
        private static string ftpServerIP = "192.168.0.120";
        private static string ftpUserID = "ljm";
        private static string ftpPassword = "ljm";
        private FtpWebRequest reqFTP;
        /// <summary>
        /// 获取FTP目录 上传 下载
        /// </summary>
        /// <returns></returns>
        public static  FTPFactory Create()
        {
            return new FTPFactory(ftpServerIP, ftpUserID, ftpPassword);
        }
      
        /// <summary>
        /// 连接FTP
        /// </summary>
        /// <param name="path"></param>
        private bool Connect(String path)
        {
            try
            {
                // 根据uri创建FtpWebRequest对象
                reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(path));
                // 指定数据传输类型
                reqFTP.UseBinary = true;
                // ftp用户名和密码
                reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);

                return true;
            }
            catch(Exception e)
            {
                return false;
            }
        }

        public FTPFactory(string ftpServerIP, string ftpUserID, string ftpPassword)
        {
            //this.ftpServerIP = ftpServerIP;
            //this.ftpUserID = ftpUserID;
            //this.ftpPassword = ftpPassword;
        }

        /// <summary>
        /// 从ftp服务器上获得文件列表
        /// </summary>
        /// <param name="path"></param>
        /// <param name="WRMethods"></param>
        /// <returns></returns>
        private string[] GetFileList(string path, string WRMethods)
        {
            string[] downloadFiles;
            StringBuilder result = new StringBuilder();
            try
            {
                Connect(path);

                reqFTP.Method = WRMethods;

                WebResponse response = reqFTP.GetResponse();

                StreamReader reader = new StreamReader(response.GetResponseStream(), System.Text.Encoding.Default);//中文文件名

                string line = reader.ReadLine();
                while (line != null)
                {
                    result.Append(line);

                    result.Append("\n");

                    line = reader.ReadLine();
                }
                if (result.Length > 0)
                {
                    result.Remove(result.ToString().LastIndexOf('\n'), 1);
                }
                reader.Close();
                response.Close();
                return result.ToString().Split('\n');                            

            }
            catch (Exception e)
            {
                //System.Windows.Forms.MessageBox.Show(e.Message);
                downloadFiles = null;
                return downloadFiles;

            }

        }

        /// <summary>
        /// 返回ftp指定的文件夹
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        public string[] GetFileList(string path)
        {
            return GetFileList("ftp://" + ftpServerIP + "/" + path, WebRequestMethods.Ftp.ListDirectory);
        }

        /// <summary>
        /// 返回ftp默认的文件夹
        /// </summary>
        /// <returns></returns>
        public string[] GetFileList()
        {
            return GetFileList("ftp://" + ftpServerIP + "/", WebRequestMethods.Ftp.ListDirectory);
        }

        /// <summary>
        /// 删除文件
        /// </summary>
        /// <param name="fileName"></param>
        public void DeleteFileName(string fileName)
        {
            try
            {
                FileInfo fileInf = new FileInfo(fileName);
                string uri = "ftp://" + ftpServerIP + "/" + fileInf.Name;
                Connect(uri);//连接                
                // 默认为true,连接不会被关闭
                // 在一个命令之后被执行
                reqFTP.KeepAlive = false;
                // 指定执行什么命令
                reqFTP.Method = WebRequestMethods.Ftp.DeleteFile;
                FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
                response.Close();
            }

            catch (Exception e)
            {
                //MessageBox.Show(e.Message, "删除错误");
            }
        }

        /// <summary>
        /// 创建目录
        /// </summary>
        /// <param name="dirName"></param>
        public void MakeDir(string dirName)
        {
            try
            {
                string uri = "ftp://" + ftpServerIP + "/" + dirName;

                Connect(uri);//连接     

                reqFTP.Method = WebRequestMethods.Ftp.MakeDirectory;

                FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();

                response.Close();
            }

            catch (Exception e)
            {
                //MessageBox.Show(e.Message);
            }

        }

        /// <summary>
        /// 删除目录
        /// </summary>
        /// <param name="dirName"></param>
        public void delDir(string dirName)
        {
            try
            {
                string uri = "ftp://" + ftpServerIP + "/" + dirName;

                Connect(uri);//连接     

                reqFTP.Method = WebRequestMethods.Ftp.RemoveDirectory;

                FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();

                response.Close();
            }

            catch (Exception e)
            {
                //MessageBox.Show(e.Message);
            }
        }

        /// <summary>
        /// 获得文件大小
        /// </summary>
        /// <param name="filename"></param>
        /// <returns></returns>
        public long GetFileSize(string filename)
        {
            long fileSize = 0;
            try
            {

                FileInfo fileInf = new FileInfo(filename);

                string uri = "ftp://" + ftpServerIP + "/" + fileInf.Name;

                Connect(uri);//连接     

                reqFTP.Method = WebRequestMethods.Ftp.GetFileSize;

                FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();

                fileSize = response.ContentLength;

                response.Close();

            }

            catch (Exception e)
            {

                //MessageBox.Show(e.Message);

            }

            return fileSize;

        }

        /// <summary>
        /// 文件改名
        /// </summary>
        /// <param name="currentFilename"></param>
        /// <param name="newFilename"></param>
        public void Rename(string currentFilename, string newFilename)
        {
            try
            {
                FileInfo fileInf = new FileInfo(currentFilename);

                string uri = "ftp://" + ftpServerIP + "/" + fileInf.Name;

                Connect(uri);//连接

                reqFTP.Method = WebRequestMethods.Ftp.Rename;

                reqFTP.RenameTo = newFilename;


                FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();

                //Stream ftpStream = response.GetResponseStream();

                //ftpStream.Close();

                response.Close();

            }

            catch (Exception e)
            {
                //MessageBox.Show(e.Message);
            }

        }

        /// <summary>
        /// 获得文件明晰
        /// </summary>
        /// <returns></returns>
        public string[] GetFilesDetailList()
        {
            return GetFileList("ftp://" + ftpServerIP + "/", WebRequestMethods.Ftp.ListDirectoryDetails);
        }

        /// <summary>
        /// 获得文件明晰
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        public string[] GetFilesDetailList(string path)
        {
            return GetFileList("ftp://" + ftpServerIP + "/" + path, WebRequestMethods.Ftp.ListDirectoryDetails);
        }
        /// <summary>
        /// 文件下载
        /// </summary>
        /// <param name="filePath"></param>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public bool Download(string filePath, string fileName)
        {
            FtpWebRequest reqFTP;

            try
            {
                FileStream outputStream = new FileStream(filePath + "\\" + fileName, FileMode.Create);

                reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + ftpServerIP + "/" + fileName));

                reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;

                reqFTP.UseBinary = true;

                reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);

                FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();

                Stream ftpStream = response.GetResponseStream();

                long cl = response.ContentLength;

                int bufferSize = 2048;

                int readCount;

                byte[] buffer = new byte[bufferSize];

                readCount = ftpStream.Read(buffer, 0, bufferSize);

                while (readCount > 0)
                {
                    outputStream.Write(buffer, 0, readCount);

                    readCount = ftpStream.Read(buffer, 0, bufferSize);
                }

                ftpStream.Close();

                outputStream.Close();

                response.Close();
                return true;
            }
            catch (Exception e)
            {
                //MessageBox.Show(e.Message);
                return false;
            }
        }
        /// <summary>
        /// 文件上传
        /// </summary>
        /// <param name="filename"></param>
        /// <returns></returns>
        public bool Upload(string filename)
        {
            try
            {
                FileInfo fileInf = new FileInfo(filename);
                string uri = "ftp://" + ftpServerIP + "/" + fileInf.Name;
                FtpWebRequest reqFTP;

                // 根据uri创建FtpWebRequest对象
                reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + ftpServerIP + "/" + fileInf.Name));

                // ftp用户名和密码
                reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);

                // 默认为true,连接不会被关闭
                // 在一个命令之后被执行
                reqFTP.KeepAlive = false;

                // 指定执行什么命令
                reqFTP.Method = WebRequestMethods.Ftp.UploadFile;

                // 指定数据传输类型
                reqFTP.UseBinary = true;

                // 上传文件时通知服务器文件的大小
                reqFTP.ContentLength = fileInf.Length;

                // 缓冲大小设置为2kb
                int buffLength = 2048;

                byte[] buff = new byte[buffLength];
                int contentLen;

                // 打开一个文件流 (System.IO.FileStream) 去读上传的文件
                FileStream fs = fileInf.OpenRead();
                try
                {
                    // 把上传的文件写入流
                    Stream strm = reqFTP.GetRequestStream();

                    // 每次读文件流的2kb
                    contentLen = fs.Read(buff, 0, buffLength);

                    // 流内容没有结束
                    while (contentLen != 0)
                    {
                        // 把内容从file stream 写入 upload stream
                        strm.Write(buff, 0, contentLen);

                        contentLen = fs.Read(buff, 0, buffLength);
                    }

                    // 关闭两个流
                    strm.Close();
                    fs.Close();
                    return true;
                }
                catch (Exception e)
                {
                    //MessageBox.Show(e.Message, "上传文件失败");
                    return false;
                }
            }
            catch (Exception e)
            {
                return false;
            }
           
        }

        public List<string> GetDirctory(string RequedstPath)
        {
            List<string> strs = new List<string>();

            try
            {
                Connect(RequedstPath);
                reqFTP.Method = WebRequestMethods.Ftp.ListDirectory;
                WebResponse response = reqFTP.GetResponse();
                StreamReader reader = new StreamReader(response.GetResponseStream(), System.Text.Encoding.Default);//中文文件名

                string line = reader.ReadLine();
                while (line != null)
                {
                    strs.Add(line);

                    line = reader.ReadLine();
                }
                reader.Close();
                response.Close();
                return strs;
            }
            catch (Exception e)
            {
            }          
            return strs;
        }
        /// <summary>
        /// 返回文件和文件夹
        /// </summary>
        /// <param name="filepath">文件夹名称(路径)</param>
        /// <returns></returns>
        public List<string> GetFileLists(string filepath)
        {
            return GetDirctory("ftp://" + ftpServerIP + "/" + filepath);
        }

        public bool OpenFtpFile(string path,string NodeText)
        {
            try
            {
                string OpenFileName = "ftp://" + ftpUserID + ":" + ftpPassword + "@" + ftpServerIP + "/" + path;
                FileInfo fileInfo = new FileInfo(NodeText);

                //如果文件存在扩展名 则打开
                if (fileInfo.Extension.Length > 0)
                {
                    ProcessStartInfo pInfo = new ProcessStartInfo();
                    pInfo.UseShellExecute = true;
                    //string fileName = OpenFileName.Substring(0, OpenFileName.LastIndexOf("/"));
                    pInfo.FileName = OpenFileName;
                    //启动进程
                    Process p = Process.Start(pInfo);
                }
                return true;
            }
            catch (Exception e)
            {
                return false;              
            }
         
        }
    }

  评论这张
 
阅读(3237)| 评论(0)
推荐 转载

历史上的今天

评论

<#--最新日志,群博日志--> <#--推荐日志--> <#--引用记录--> <#--博主推荐--> <#--随机阅读--> <#--首页推荐--> <#--历史上的今天--> <#--被推荐日志--> <#--上一篇,下一篇--> <#-- 热度 --> <#-- 网易新闻广告 --> <#--右边模块结构--> <#--评论模块结构--> <#--引用模块结构--> <#--博主发起的投票-->
 
 
 
 
 
 
 
 
 
 
 
 
 
 

页脚

网易公司版权所有 ©1997-2017