码迷,mamicode.com
首页 > 其他好文 > 详细

Ftp文件操作

时间:2014-09-30 10:58:22      阅读:240      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   io   os   ar   for   文件   数据   

public class FtpTools
    {
        static readonly string ftpServerIP = ConfigurationManager.AppSettings["FtpAddress"];
        static readonly string ftpUserID = ConfigurationManager.AppSettings["FtpUserName"];
        static readonly string ftpPassword = ConfigurationManager.AppSettings["FtpPassword"];
        static readonly string headPath = ConfigurationManager.AppSettings["FileUploadDir"];

        /// <summary>
        /// 连接ftp
        /// </summary>
        /// <param name="path"></param>
        private static FtpWebRequest Connect(String path)
        {
            // 根据uri创建FtpWebRequest对象
            FtpWebRequest reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpServerIP + path));
            // 指定数据传输类型
            reqFTP.UseBinary = true;
            reqFTP.UsePassive = false;
            // ftp用户名和密码
            SecureString sPassword = new SecureString();
            foreach (var p in ftpPassword)
            {
                sPassword.AppendChar(p);
            }
            reqFTP.Credentials = new NetworkCredential(ftpUserID, sPassword);
            return reqFTP;
        }

        /// <summary>
        /// 创建目录
        /// </summary>
        /// <param name="dirName"></param>
        private static void MakeDir(string dirName)
        {
            var dirNameList = dirName.Split(/);
            string nowDirName = "";
            for (int i = 0; i < dirNameList.Length; i++)
            {
                if (string.IsNullOrEmpty(dirNameList[i]))
                {
                    return;
                }
                if (i == 0)
                {
                    nowDirName += dirNameList[i];
                }
                else
                {
                    nowDirName += "/" + dirNameList[i];
                }
                if (!DirectoryExist(nowDirName))
                {
                    FtpWebRequest reqFTP = Connect(nowDirName);//连接
                    reqFTP.Method = WebRequestMethods.Ftp.MakeDirectory;
                    FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
                    response.Close();
                    reqFTP.Abort();
                }
            }

        }

        /// <summary>
        /// 目录是否存在(根目录必须有)
        /// </summary>
        /// <param name="dirName"></param>
        /// <returns></returns>
        public static bool DirectoryExist(string dirName)
        {
            bool result = false;
            try
            {
                if (!dirName.Contains("/"))
                {
                    return true;
                }
                if (dirName[dirName.Length - 1] == /)
                {
                    dirName = dirName.Remove(dirName.Length - 1);
                }
                var array = dirName.Split(/);
                var nowDirName = array[array.Length - 1];
                var rootDir = string.Join("/", array.Take(array.Length - 1));
                FtpWebRequest reqFTP = Connect(rootDir);//连接
                //指定FTP操作类型为创建目录
                reqFTP.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
                //获取FTP服务器的响应
                FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
                StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.Default);
                StringBuilder streamStr = new StringBuilder();
                string line = "";
                while (true)
                {
                    line = sr.ReadLine();
                    if (line == null)
                    {
                        break;
                    }
                    line = line.Remove(0, line.IndexOf("<DIR>") + 5).Trim();
                    if (nowDirName == line)
                    {
                        result = true;
                    }
                }
                response.Close();
                reqFTP.Abort();
            }
            catch
            {
                return false;
            }
            return result;
        }

        /// <summary>
        /// 检查文件是否存在
        /// </summary>
        /// <param name="ftpPath"></param>
        /// <param name="ftpName"></param>
        /// <returns></returns>
        public static bool fileCheckExist(string ftpPath, string ftpName)
        {
            bool success = false;
            FtpWebResponse webResponse = null;
            StreamReader reader = null;
            try
            {
                FtpWebRequest ftpWebRequest = Connect(ftpPath);//连接;
                ftpWebRequest.Method = WebRequestMethods.Ftp.ListDirectory ;
                ftpWebRequest.KeepAlive = false;
                ftpWebRequest.Proxy = null; 

                webResponse = (FtpWebResponse)ftpWebRequest.GetResponse();
                if (webResponse != null)
                {
                    reader = new StreamReader(webResponse.GetResponseStream(), Encoding.Default);
                    string line = reader.ReadLine();
                    while (line != null)
                    {
                        if (line == ftpName)
                        {
                            success = true;
                            break;
                        }
                        line = reader.ReadLine();
                    }
                }
            }
            catch (Exception)
            {
                success = false;
            }
            finally
            {
                if (reader != null)
                {
                    reader.Close();
                }
                if (webResponse != null)
                {
                    webResponse.Close();
                }
            }
            return success;
        }


        /// <summary>
        /// ftp上传
        /// </summary>
        /// <param name="stream"></param>
        /// <param name="dirName"></param>
        /// <param name="fileFullName"></param>
        public static void Upload(string dirName, string fileFullName, byte[] FileData)
        {
            if (!DirectoryExist(dirName))
            {
                MakeDir(dirName);
            }
            FtpWebRequest reqFTP = Connect(fileFullName);//连接
            reqFTP.Proxy = null;
            // 默认为true,连接不会被关闭
            // 在一个命令之后被执行
            reqFTP.KeepAlive = false;
            // 指定执行下载
            reqFTP.Method = WebRequestMethods.Ftp.UploadFile;
            // 上传文件时通知服务器文件的大小
            reqFTP.ContentLength = FileData.Length;
            // 把上传的文件写入流
            Stream strm = reqFTP.GetRequestStream();
            strm.Write(FileData, 0, FileData.Length);
            strm.Close();
            reqFTP.Abort();
        }

        /// <summary>
        /// ftp下载
        /// </summary>
        /// <param name="fullFileName"></param>
        public static byte[] Download(string fullFileName)
        {
            FtpWebRequest reqFTP = Connect(fullFileName);//连接
            reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
            FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
            Stream ftpStream = response.GetResponseStream();
            int bufferSize = 2048;
            int readCount = 0;
            int length = 0;
            List<byte> tmpResult = new List<byte>();
            byte[] result = new byte[0];
            byte[] buffer = new byte[bufferSize];
            try
            {
                MemoryStream ms = new MemoryStream();
                readCount = ftpStream.Read(buffer, 0, bufferSize);
                tmpResult.AddRange(buffer);
                length += readCount;
                while (readCount > 0)
                {
                    ms.Write(buffer, 0, readCount);
                    readCount = ftpStream.Read(buffer, 0, bufferSize);
                    tmpResult.AddRange(buffer);
                }
                ms.Flush();
                ms.Close();
                ftpStream.Close();
                response.Close();
                reqFTP.Abort();
                result = ms.ToArray();
            }
            catch { throw; }
            finally { 
                //FileTools.DelFile(tmpPath);
            }
            return result;
        }

        /// <summary>  
        /// 删除文件
        /// </summary>  
        /// <param name="Path">文件路径</param> 
        public static void DelFile(string Path)
        {
            FtpWebRequest reqFTP = Connect(Path);//连接
            reqFTP.Method = WebRequestMethods.Ftp.DeleteFile;
            reqFTP.GetResponse();
            reqFTP.Abort();
        }

 

Ftp文件操作

标签:style   blog   color   io   os   ar   for   文件   数据   

原文地址:http://www.cnblogs.com/qinming/p/4001344.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!