首页 > 代码库 > FTP上传指定文件夹及其文件到服务器

FTP上传指定文件夹及其文件到服务器

1、在服务器端的IIS上建立一个FTP站点

image 

注意事项:路径关联到你要存放(上传内容)的文件夹名称;

                    指定这个FTP站点的ip地址和端口号

2、本地准备代码

-------------------------------2.1上传类---------------------------------------------------------

    public class Up
    {
        /// <summary>
        ///   上传文件菜单
        /// </summary>
        /// <param name="sender"> </param>
        /// <param name="e"> </param>
        public static string FolderN;
        /// <summary>
        ///   遍历本地文件夹上传整个文件夹到FTP
        /// </summary>
        /// z
        /// <param name="path"> </param>
        public static string NPath="";
        private string serverIp ="192.168.1.50:25";//服务器的IP及其端口号 [仅凭这个就可以找到server端的文件夹名称,因为端口号是唯一的,已经做好了关联;因此FTP站点的名称、server端文件夹的名称就显得无足轻重了(用不到);IP+端口号就能知道上传内容放到哪里面了]

        private string serverUser ="administrator";//服务器登录名
        private string serverPwd = "admin?123";//服务器登录密码

        public string GFolder;
        private FtpWebRequest reqFTP;

        //上传文件夹(递归调用)
        public void UpDir(string aimPath)
        {
            try
            {
                // 检查目标目录是否以目录分割字符结束如果不是则添加之
                if (aimPath[aimPath.Length - 1] != Path.DirectorySeparatorChar)
                    aimPath += Path.DirectorySeparatorChar;
                if (NPath == "" || NPath == null)
                {
                    FolderN = aimPath.Split(‘\\‘)[aimPath.Split(‘\\‘).Length-2];
                    NPath = NPath + FolderN;
                    MakeDir(NPath, serverIp, serverUser, serverPwd);
                }
                // 得到源目录的文件列表,里面是包含文件以及目录路径的一个数组
                string[] fileList = Directory.GetFileSystemEntries(aimPath);
                // 遍历所有的文件和目录
                foreach (string file in fileList)
                {
                    string[] a = file.Split(‘\\‘);
                    string fname = a[a.Length - 1];
                    NPath = file.Remove(0, GFolder.Length).Replace("\\", "//");
                    if (NPath.StartsWith("//"))
                    {
                        NPath = NPath.Remove(0, 2);
                    }
                    // 先当作目录处理如果存在这个目录就递归Delete该目录下面的文件
                    if (Directory.Exists(file))
                    {
                        string aa = file;
                        NPath = file.Remove(0, GFolder.Length).Replace("\\", "//");
                        if (NPath.StartsWith("//"))
                        {
                            NPath = NPath.Remove(0, 2);
                        }
                        MakeDir(NPath, serverIp, serverUser, serverPwd);
                        UpDir(file);
                    }
                    else
                    {
                        Upload(file, serverIp, serverUser, serverPwd,NPath.Remove(NPath.LastIndexOf("//")) + "/");
                    }
                }
            }
            catch
            {
            }
        }
        //去除空格
        private string QCKG(string str)
        {
            string a = "";
            CharEnumerator CEnumerator = str.GetEnumerator();
            while (CEnumerator.MoveNext())
            {
                byte[] array = new byte[1];
                array = Encoding.ASCII.GetBytes(CEnumerator.Current.ToString());
                int asciicode = (array[0]);
                if (asciicode != 32)
                {
                    a += CEnumerator.Current.ToString();
                }
            }
            return a;
        }

        public bool Upload(string filename, string ftpServerIP, string ftpUserID, string ftpPassword,string path)
        {
            if (path == null)
                path = "";
            bool success = true;
            FileInfo fileInf = new FileInfo(filename);
            int allbye = (int)fileInf.Length;
            string newFileName;
            if (fileInf.Name.IndexOf("#") == -1)
            {
                newFileName = QCKG(fileInf.Name);
            }
            else
            {
                newFileName = fileInf.Name.Replace("#", "#");
                newFileName = QCKG(newFileName);
            }
            string uri;
            if (path.Length == 0)
                uri = "ftp://" + ftpServerIP + "/" + newFileName;
            else
                uri = "ftp://" + ftpServerIP + "/" + path + newFileName;
            FtpWebRequest reqFTP;
            // 根据uri创建FtpWebRequest对象
            reqFTP = (FtpWebRequest)WebRequest.Create(new Uri(uri));
            // ftp用户名和密码
            reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
            // 默认为true,连接不会被关闭
            // 在一个命令之后被执行
            reqFTP.KeepAlive = false;
            // 指定执行什么命令
            reqFTP.Method = WebRequestMethods.Ftp.UploadFile;
            // 指定数据传输类型
            reqFTP.UseBinary = true;
            // 上传文件时通知服务器文件的大小
            reqFTP.ContentLength = fileInf.Length;
            int buffLength = 2048; // 缓冲大小设置为2kb
            byte[] buff = new byte[buffLength];
            // 打开一个文件流 (System.IO.FileStream) 去读上传的文件
            FileStream fs = fileInf.OpenRead();
            try
            {
                // 把上传的文件写入流
                Stream strm = reqFTP.GetRequestStream();
                // 每次读文件流的2kb
                int 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();
            }
            catch
            {
                success = false;
            }
            return success;
        }
        //创建目录
        public void MakeDir(string dirName, string ftpServerIP, string ftpUserID, string ftpPassword)
        {
            try
            {
                string uri = "ftp://" + ftpServerIP + "/" + dirName;
                Connect(uri, ftpUserID, ftpPassword); //连接      
                reqFTP.Method = WebRequestMethods.Ftp.MakeDirectory;
                FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
                response.Close();
            }
            catch
            {
            }
        }
        //连接ftp
        public void Connect(String path, string ftpUserID, string ftpPassword)
        {
            // 根据uri创建FtpWebRequest对象
            reqFTP = (FtpWebRequest)WebRequest.Create(new Uri(path));
            // 指定数据传输类型
            reqFTP.UseBinary = true;
            // ftp用户名和密码
            reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
        }
    }

 ---------------------------------------------------2.2------------------------------------------------------------------

调用FTP上传类

                            string dirPath="d:\CopyData";//指定本地要上传的文件夹路径

                            Up up = new Up();
                            up.GFolder = Directory.GetParent(dirPath).FullName;//get文件夹名称
                            up.UpDir(dirPath);

原理:对指定的文件夹进行递归,遍历其下每一级的文件夹/文件,上传······