C# FTP上传文件及文件夹至服务器代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Net;
using System.Globalization;
using System.Text;
using System.Net;

namespace FTPwebsite
{
    public partial class test3 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }
        private string ftpServerIP = "192.168.1.1";//服务器ip
        private string ftpUserID = "admin";//用户名
        private string ftpPassword = "123456";//密码

        #region 上传文件

        /// 
        /// 上传文件
        /// 
        /// 要上传到FTP服务器的本地文件
        /// FTP地址
        public void UpLoadFile(string localFile, string ftpPath)
        {
            if (!File.Exists(localFile))
            {
                Response.Write("文件:“" + localFile + "” 不存在!");
                return;
            }
            FileInfo fileInf = new FileInfo(localFile);
            FtpWebRequest reqFTP;

            reqFTP = (FtpWebRequest)FtpWebRequest.Create(ftpPath);// 根据uri创建FtpWebRequest对象 
            reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);// ftp用户名和密码
            reqFTP.KeepAlive = false;// 默认为true,连接不会被关闭 // 在一个命令之后被执行
            reqFTP.Method = WebRequestMethods.Ftp.UploadFile;// 指定执行什么命令
            reqFTP.UseBinary = true;// 指定数据传输类型
            reqFTP.ContentLength = fileInf.Length;// 上传文件时通知服务器文件的大小
            int buffLength = 2048;// 缓冲大小设置为2kb
            byte[] buff = new byte[buffLength];
            int contentLen;

            // 打开一个文件流 (System.IO.FileStream) 去读上传的文件
            FileStream fs = fileInf.OpenRead();
            try
            {
                Stream strm = reqFTP.GetRequestStream();// 把上传的文件写入流
                contentLen = fs.Read(buff, 0, buffLength);// 每次读文件流的2kb

                while (contentLen != 0)// 流内容没有结束
                {
                    // 把内容从file stream 写入 upload stream
                    strm.Write(buff, 0, contentLen);
                    contentLen = fs.Read(buff, 0, buffLength);
                }
                // 关闭两个流
                strm.Close();
                fs.Close();
                Response.Write("文件【" + ftpPath + "/" + fileInf.Name + "】上传成功!
"); } catch (Exception ex) { Response.Write("上传文件【" + ftpPath+"/"+fileInf.Name + "】时,发生错误:" + ex.Message + "
"); } } #endregion #region 上传文件夹 /// /// 上传整个目录 /// /// 要上传的目录的上一级目录 /// FTP路径 /// 要上传的目录名 /// FTP用户名(匿名为空) /// FTP登录密码(匿名为空) public void UploadDirectory(string localDir, string ftpPath, string dirName) { string dir = localDir +dirName+ @"\"; //获取当前目录(父目录在目录名) //检测本地目录是否存在 if (!Directory.Exists(dir)) { Response.Write("本地目录:“" + dir + "” 不存在!
"); return; } //检测FTP的目录路径是否存在 if (!CheckDirectoryExist(ftpPath, dirName)) { MakeDir(ftpPath, dirName);//不存在,则创建此文件夹 } List> infos = GetDirDetails(dir); //获取当前目录下的所有文件和文件夹 //先上传文件 //Response.Write(dir + "下的文件数:" + infos[0].Count.ToString() + "
"); for (int i = 0; i < infos[0].Count; i++) { Console.WriteLine(infos[0][i]); UpLoadFile(dir + infos[0][i], ftpPath + dirName + @"/" + infos[0][i]); } //再处理文件夹 //Response.Write(dir + "下的目录数:" + infos[1].Count.ToString() + "
"); for (int i = 0; i < infos[1].Count; i++) { UploadDirectory(dir, ftpPath + dirName + @"/", infos[1][i]); //Response.Write("文件夹【" + dirName + "】上传成功!
"); } } /// /// 判断ftp服务器上该目录是否存在 /// /// FTP路径目录 /// 目录上的文件夹名称 /// private bool CheckDirectoryExist(string ftpPath, string dirName) { bool flag = true; try { //实例化FTP连接 FtpWebRequest ftp = (FtpWebRequest)FtpWebRequest.Create(ftpPath + dirName); ftp.Credentials = new NetworkCredential(ftpUserID, ftpPassword); ftp.Method = WebRequestMethods.Ftp.ListDirectory; FtpWebResponse response = (FtpWebResponse)ftp.GetResponse(); response.Close(); } catch (Exception) { flag = false; } return flag; } /// /// 创建文件夹 /// /// FTP路径 /// 创建文件夹名称 public void MakeDir(string ftpPath, string dirName) { FtpWebRequest reqFTP; try { string ui = (ftpPath + dirName).Trim(); reqFTP = (FtpWebRequest)FtpWebRequest.Create(ui); reqFTP.Method = WebRequestMethods.Ftp.MakeDirectory; reqFTP.UseBinary = true; reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword); FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse(); Stream ftpStream = response.GetResponseStream(); ftpStream.Close(); response.Close(); Response.Write("文件夹【" + dirName + "】创建成功!
"); } catch (Exception ex) { Response.Write("新建文件夹【" + dirName+"】时,发生错误:" + ex.Message); } } /// /// 获取目录下的详细信息 /// /// 本机目录 /// private List> GetDirDetails(string localDir) { List> infos = new List>(); try { infos.Add(Directory.GetFiles(localDir).ToList()); //获取当前目录的文件 infos.Add(Directory.GetDirectories(localDir).ToList()); //获取当前目录的目录 for (int i = 0; i < infos[0].Count; i++) { int index = infos[0][i].LastIndexOf(@"\"); infos[0][i] = infos[0][i].Substring(index + 1); } for (int i = 0; i < infos[1].Count; i++) { int index = infos[1][i].LastIndexOf(@"\"); infos[1][i] = infos[1][i].Substring(index + 1); } } catch (Exception ex) { ex.ToString(); } return infos; } #endregion protected void Button1_Click(object sender, EventArgs e) { //FTP地址 string ftpPath = "ftp://192.168.1.1/"; //本机要上传的目录的父目录 string localPath = "E:\\发布\\"; //要上传的目录名 string fileName = "test1"; FileInfo fi = new FileInfo(localPath); //判断上传文件是文件还是文件夹 if ((fi.Attributes & FileAttributes.Directory) != 0) { //dir 如果是文件夹,则调用[上传文件夹]方法 UploadDirectory(localPath, ftpPath, fileName); } else { //file 如果是文件,则调用[上传文件]方法 UpLoadFile(localPath + fileName, ftpPath); } } } }

你可能感兴趣的:(【C#】,【ASP.NET】)