FTP上传文件到服务器

一、初始化上传控件。

1、我们这里用dropzone.js作为上传控件,下载地址http://www.dropzonejs.com/

2、这里我们使用一个div元素作为dropzone载体。

<div class="tray-bin ml10 mr10" style="min-height: 250px;">
    <h5 class="text-muted mt10 fw600">
        <i class="fa fa-exclamation-circle text-info fa-lg"></i> 上传外部文件
    </h5>
    <div class="dropzone dropzone-sm" id="dropZone">
        <div class="fallback">
            <input name="file" type="file" multiple />
        </div>
    </div>
</div>

3、这里我们使用Dropzone 附带的 jQuery 插件创建dropzone,(示例仅作参考,如果想实现自己想要的功能还需要参照官方给出的文档进行修改)。

function InitDropzone() {
    //Dropzone的初始化,dropZone为div的id
    $("#dropZone").dropzone({
        //指明了文件提交到哪个页面。
        url: "/Job/Exercise/Upload",
        //相当于<input>元素的name属性,默认为file。
        paramName: "file",
        //最大文件大小,单位是 MB。
        maxFilesize: 1024,
        //默认为null,可以指定为一个数值,限制最多文件数量。
        maxFiles: 1,
        //默认false。如果设为true,则会给文件添加一个删除链接
        addRemoveLinks: true,
        //指明允许上传的文件类型,格式是逗号分隔的 MIME type 或者扩展名。例如:image/*,application/pdf,.psd,.obj
        acceptedFiles: ".sdb,.srk",
        //指明是否允许 Dropzone 一次提交多个文件。默认为false。如果设为true,则相当于 HTML 表单添加multiple属性。
        uploadMultiple: false,
        //如果设定,则会作为额外的 header 信息发送到服务器。例如:{"custom-header": "value"}
        //headers:{"custom-header": "value"},
        //关闭自动上传功能,默认会true会自动上传,也就是添加一张图片向服务器发送一次请求
        autoProcessQueue: true,
        //没有任何文件被添加的时候的提示文本
        dictDefaultMessage: '<i class="fa fa-cloud-upload"></i> \
                 <span class="main-text"><b>点击选择题库文件</b></span> <br /> \
                 <span class="sub-text">或将文件拖动到这里,单次最多上传1个文件</span> \
                ',
        //文件类型被拒绝时的提示文本
        dictInvalidInputType: "",
        //文件大小过大时的提示文本。
        dictFileTooBig: "文件过大({{filesize}}MB). 上传文件最大支持: {{maxFilesize}}MB.",
        //取消上传链接的文本
        dictCancelUpload: "取消上传",
        //取消上传确认信息的文本。
        dictCancelUploadConfirmation: "你确定要取消上传吗?",
        //移除文件链接的文本。
        dictRemoveFile: "移除文件",
        //超过最大文件数量的提示文本。
        dictMaxFilesExceeded: "您一次最多只能上传{{maxFiles}}个文件",
        //如果该文件与文件类型不匹配所示的错误消息
        dictInvalidFileType: "请上传题库文件",
        //如果服务器响应无效时的错误消息。{{statusCode}}将被替换的服务器状态代码
        dictResponseError: '文件上传失败!',
        //一个函数,在 Dropzone 初始化的时候调用,可以用来添加自己的事件监听器。
        init: function () {
            //当一个文件被添加到列表中
            this.on("addedfile", function (file) {

            });
            //从列表中删除一个文件。你可以监听该事件然后从您的服务器删除文件
            this.on("removedfile", function (file) {
                if (file.fileName == undefined) { return; }

                var url = "/Job/Exercise/DeleteFile";
                window.setTimeout(function () {
                    var postData = {
                        fileName: file.fileName
                    }
                    AjaxJson(url, postData, function (data) {
                        //alertDialog(data.Message, 1);
                    });
                }, 500);
            });
            //当文件的数量达到maxFiles限制时调用
            this.on("maxfilesreached", function (file) {

            });
            //由于文件数量达到 maxFiles 限制数量被拒绝时调用
            this.on("maxfilesexceeded", function (file) {
                this.removeFile(file);
            });
            //当上传队列中的所有文件上传完成时调用
            this.on("queuecomplete", function (file) {

            });
            //文件已经成功上传触发。file为第一个参数,获取服务器响应作为第二个参数。(这一事件在finished之前触发。
            this.on("success", function (file, response) {
                file.fileName = response.FileName;

                if (response.Result) {
                    $("#FileName").val(response.FileName);
                    $("#FilePath").val(response.FilePath);
                    $("#FileSize").val(response.FileSize);
                } else {
                    alertDialog(response.Message, -1);
                    this.removeFile(file);
                }
            });
            //发生一个错误。接收errorMessage作为第二个参数,如果错误是由于XMLHttpRequest xhr对象为第三个参数。
            this.on("error", function (file, errorMessage) {
                alertDialog(errorMessage, -1);
                this.removeFile(file);
            });
            //上传成功或错误时。
            this.on("complete", function (file) {

            });
        },
    });
}

二、后台上传功能。

1、保存文件到服务器,并上传到FTP服务器。

/// <summary>
/// 上传文件
/// </summary>
/// <returns></returns>
public JsonResult Upload()
{
    #region 局部变量
    var result = true;
    var checkResult = false;

    string message = string.Empty;
    string ftpMessage = string.Empty;
    string savePath = string.Empty;
    string fileName = string.Empty;
    string fileSize = string.Empty;
    string filePath = string.Empty;
    var currentDir = string.Empty;

    List<string> dirList = new List<string>();

    FtpWeb ftpWeb = null;
    HttpPostedFileBase file = null;
    var topicdb = new T_zy_topicdb();
    var topicdbftp = new T_zy_topicdbftp();
    #endregion

    try
    {
        #region 判断是否为有效文件
        file = Request.Files[0];
        if (file.ContentLength <= 0)
        {
            result = false;
            message = "不能上传零字节的文件";
            return Json(new { Result = result, Message = message });
        }
        #endregion

        #region 保存文件
        //上传文件临时路径
        savePath = SysFun.GetAppUploadPath() + SysFun.GetTopicDBSavePath();
        if (!Directory.Exists(savePath)) Directory.CreateDirectory(savePath);
        fileName = Path.GetFileName(file.FileName);
        fileSize = SysFun.FileSize(file.ContentLength);
        filePath = string.Format("{0}\\{1}", savePath, fileName);
        //保存文件
        file.SaveAs(filePath);
        #endregion

        #region 上传到FTP目录
        topicdbftp = bllTopicDBFTP.SelectWhere("1=1");
        checkResult = FtpWebTest.CheckFtp(topicdbftp.IP, topicdbftp.UserName, topicdbftp.Password, topicdbftp.Port, topicdbftp.Pattern.Value, topicdbftp.Anonymous.Value, out ftpMessage);
        if (checkResult)
        {
            ftpWeb = new FtpWeb(topicdbftp.IP, SysFun.GetUploadDir(), topicdbftp.UserName, topicdbftp.Password, topicdbftp.Port, 3000, topicdbftp.Pattern.Value, topicdbftp.Anonymous.Value);
            dirList = SysFun.GetTopicDBSavePath().Split(new string[] { "\\" }, StringSplitOptions.RemoveEmptyEntries).ToList();
            foreach (var dirName in dirList)
            {
                if (!ftpWeb.DirectoryExist(dirName)) ftpWeb.MakeDir(dirName);
                currentDir = string.Format("/{0}/", dirName);
                ftpWeb.GotoDirectory(currentDir, false);
            }
            ftpWeb.Upload(filePath);
            result = true;
            message = "上传成功!";
        }
        else
        {
            result = false;
            message = "FTP上传失败,原因:" + ftpMessage;
            DeleteLocalEnvFile(filePath, ftpWeb);
        }
        #endregion
    }
    catch (Exception ex)
    {
        result = false;
        message = ex.Message;
        DeleteLocalEnvFile(filePath, ftpWeb);
    }

    return Json(new { Result = result, Message = message, FileName = fileName, FileSize = fileSize, FilePath = filePath });
}

2、以下是上传文件用到的帮助类。

/// <summary>
/// 计算文件大小函数(保留两位小数),Size为字节大小
/// </summary>
/// <param name="Size">初始文件大小</param>
/// <returns></returns>
public static string FileSize(long Size)
{
    string m_strSize = "";
    long FactSize = 0;
    FactSize = Size;
    if (FactSize < 1024.00)
        m_strSize = FactSize.ToString("F2") + " Byte";
    else if (FactSize >= 1024.00 && FactSize < 1048576)
        m_strSize = (FactSize / 1024.00).ToString("F2") + " K";
    else if (FactSize >= 1048576 && FactSize < 1073741824)
        m_strSize = (FactSize / 1024.00 / 1024.00).ToString("F2") + " M";
    else if (FactSize >= 1073741824)
        m_strSize = (FactSize / 1024.00 / 1024.00 / 1024.00).ToString("F2") + " G";
    return m_strSize;
}
public class FtpWebTest
{
    static Dictionary<string, string> StatusList;

    /// <summary>
    /// 检查FTP连接(带地址)
    /// </summary>
    /// <param name="ftpUserID">用户名</param>
    /// <param name="ftpPassword">密码</param>
    /// <param name="port">端口号</param>
    /// <param name="pattern">模式</param>
    /// <param name="ftpAnonymous">匿名</param>
    /// <param name="message">返回信息</param>
    /// <returns></returns>
    public static bool CheckFtp(string ftpUserID, string ftpPassword, string port, bool pattern, bool ftpAnonymous, out string message)
    {
        return CheckFtp("", ftpUserID, ftpPassword, port, pattern, ftpAnonymous, out message);
    }
    /// <summary>
    /// 检查FTP连接(不带地址)
    /// </summary>
    /// <param name="ip">地址</param>
    /// <param name="ftpUserID">用户名</param>
    /// <param name="ftpPassword">密码</param>
    /// <param name="port">端口号</param>
    /// <param name="pattern">模式</param>
    /// <param name="ftpAnonymous">匿名</param>
    /// <param name="message">返回信息</param>
    /// <returns></returns>
    public static bool CheckFtp(string ip, string ftpUserID, string ftpPassword, string port, bool pattern, bool ftpAnonymous, out string message)
    {
        int statusCode = 0;
        bool checkResult = false;
        string serverIP = string.Empty;
        string ftpURL = string.Empty;
        FtpWebRequest ftpRequest = null;
        FtpWebResponse ftpResponse = null;

        try
        {
            if (string.IsNullOrEmpty(ip)) serverIP = GetIPAddress(); else serverIP = ip;
            if (string.IsNullOrEmpty(serverIP)) throw new Exception("获取服务器IP地址失败");
            ftpURL = string.Format("ftp://{0}:{1}/", serverIP, port);
            ftpRequest = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURL));
            if (!ftpAnonymous)
            {
                ftpRequest.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
            }
            ftpRequest.UsePassive = pattern;
            ftpRequest.UseBinary = true;
            ftpRequest.Method = WebRequestMethods.Ftp.ListDirectory;
            ftpRequest.Timeout = 3000;
            ftpResponse = ftpRequest.GetResponse() as FtpWebResponse;
            if (ftpResponse.StatusCode == FtpStatusCode.OpeningData || ftpResponse.StatusCode == FtpStatusCode.DataAlreadyOpen)
            {
                checkResult = true;
            }
            statusCode = (int)ftpResponse.StatusCode;
            message = GetStatusMessage(statusCode.ToString());
            ftpResponse.Close();
        }
        catch (WebException ex)
        {
            checkResult = false;
            message = ex.Message;
        }
        catch (Exception ex)
        {
            checkResult = false;
            message = ex.Message;
        }

        return checkResult;
    }
    private static string GetStatusMessage(string statusCode)
    {
        GetStatusName();

        if (StatusList.ContainsKey(statusCode))
        {
            return StatusList[statusCode];
        }
        else
        {
            return "检测失败";
        }
    }
    private static void GetStatusName()
    {
        StatusList = new Dictionary<string, string>();
        StatusList.Add("110", "响应包含一个重新启动标记回复");
        StatusList.Add("120", "此服务现在不可用,请稍后再试您的请求");
        StatusList.Add("125", "数据连接已打开并且请求的传输已开始");
        StatusList.Add("150", "服务器正在打开数据连接");
        StatusList.Add("200", "命令成功完成");
        StatusList.Add("202", "服务器未执行该命令");
        StatusList.Add("220", "服务器已能进行用户登录操作");
        StatusList.Add("221", "服务器正在关闭管理连接");
        StatusList.Add("226", "服务器正在关闭数据连接,并且请求的文件操作成功");
        StatusList.Add("250", "请求的文件操作成功完成");
        StatusList.Add("331", "服务器需要提供密码");
        StatusList.Add("332", "服务器需要提供登录帐户");
        StatusList.Add("421", "此服务不可用");
        StatusList.Add("425", "无法打开数据连接");
        StatusList.Add("426", "连接已关闭");
        StatusList.Add("451", "发生了阻止完成请求操作的错误");
        StatusList.Add("452", "不能执行请求的操作,因为服务器上没有足够的空间");
        StatusList.Add("500", "命令具有语法错误或不是服务器可识别的命令");
        StatusList.Add("501", "一个或多个命令参数具有语法错误");
        StatusList.Add("502", "FTP 服务器未执行该命令");
        StatusList.Add("530", "登录信息必须发送到服务器");
        StatusList.Add("532", "需要服务器上的用户帐户");
        StatusList.Add("550", "无法对指定文件执行请求的操作,原因是该文件不可用");
        StatusList.Add("551", "不能采取请求的操作,因为指定的页类型是未知的");
        StatusList.Add("552", "不能执行请求的操作");
        StatusList.Add("553", "无法对指定文件执行请求的操作");
    }
    private static string GetIPAddress()
    {
        IPAddress[] arrIPAddresses = Dns.GetHostAddresses(Dns.GetHostName());
        foreach (IPAddress ip in arrIPAddresses)
        {
            if (ip.AddressFamily.Equals(AddressFamily.InterNetwork))
            {
                return ip.ToString();
            }
        }
        return "";
    }
}
public class FtpWeb
    {
        string ftpServerIP;
        string ftpRemotePath;
        string ftpUserID;
        string ftpPassword;
        string ftpURI;
        string ftpPort;
        int timeOut;
        bool model;
        bool anonymous;
        /// <summary> 
        /// 连接FTP 
        /// </summary> 
        /// <param name="FtpServerIP">FTP连接地址</param> 
        /// <param name="FtpRemotePath">指定FTP连接成功后的当前目录, 如果不指定即默认为根目录</param> 
        /// <param name="FtpUserID">用户名</param> 
        /// <param name="FtpPassword">密码</param> 
        public FtpWeb(string FtpServerIP, string FtpRemotePath, string FtpUserID, string FtpPassword, string FtpPort, int TimeOut, bool Model, bool Anonymous)
        {
            ftpServerIP = FtpServerIP;
            ftpRemotePath = FtpRemotePath;
            ftpUserID = FtpUserID;
            ftpPassword = FtpPassword;
            ftpPort = FtpPort;
            timeOut = TimeOut;
            model = Model;
            anonymous = Anonymous;
            ftpURI = string.Format("ftp://{0}:{1}/{2}/", ftpServerIP, FtpPort, ftpRemotePath);
        }
        public FtpWeb(string FtpServerIP, string FtpRemotePath, string FtpUserID, string FtpPassword, string FtpPort)
        {
            ftpServerIP = FtpServerIP;
            ftpRemotePath = FtpRemotePath;
            ftpUserID = FtpUserID;
            ftpPassword = FtpPassword;
            ftpPort = FtpPort;
            timeOut = 10000;
            model = true;
            anonymous = true;
            ftpURI = string.Format("ftp://{0}:{1}/{2}/", ftpServerIP, FtpPort, ftpRemotePath);
            //ftpURI = string.Format("ftp://{0}:{1}/", ftpServerIP, FtpPort);
        }
        /// <summary> 
        /// 上传 
        /// </summary> 
        /// <param name="filename"></param> 
        public void Upload(string filename)
        {
            FileInfo fileInf = new FileInfo(filename);
            string uri = ftpURI + fileInf.Name;
            FtpWebRequest reqFTP;
            reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
            if (!anonymous)
                reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
            reqFTP.KeepAlive = false;
            reqFTP.Timeout = timeOut;
            reqFTP.UsePassive = model;
            reqFTP.Method = WebRequestMethods.Ftp.UploadFile;
            reqFTP.UseBinary = true;
            reqFTP.ContentLength = fileInf.Length;
            int buffLength = 2048;
            byte[] buff = new byte[buffLength];
            int contentLen;
            FileStream fs = fileInf.OpenRead();
            try
            {
                Stream strm = reqFTP.GetRequestStream();
                contentLen = fs.Read(buff, 0, buffLength);
                while (contentLen != 0)
                {
                    strm.Write(buff, 0, contentLen);
                    contentLen = fs.Read(buff, 0, buffLength);
                }
                strm.Close();
                fs.Close();
            }
            catch (Exception ex)
            {
                throw new Exception("FTP上传文件过程中发生错误:" + ex.Message);
            }
        }
        public void Download(string TopicDBCode, string filePath, string fileName)
        {
            Download(TopicDBCode, filePath, fileName, "");
        }
        /// <summary> 
        /// 下载 
        /// </summary> 
        /// <param name="filePath"></param> 
        /// <param name="fileName"></param> 
        public void Download(string TopicDBCode, string filePath, string fileName, string Uri)
        {
            FtpWebRequest reqFTP;
            string FileName = "";
            FtpWebResponse response = null;
            Stream ftpStream = null;
            FileStream outputStream = null;
            try
            {
                FileName = filePath + Path.DirectorySeparatorChar + fileName;
                if (!Directory.Exists(filePath))
                    Directory.CreateDirectory(filePath);
                outputStream = new FileStream(FileName, FileMode.Create);
                string Url = ftpURI;
                if (!string.IsNullOrEmpty(Uri))
                    Url += Uri;
                reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(Url + fileName));
                reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
                reqFTP.UseBinary = true;
                reqFTP.Timeout = timeOut;
                reqFTP.UsePassive = model;
                if (!anonymous)
                    reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
                response = (FtpWebResponse)reqFTP.GetResponse();
                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();
            }
            catch (Exception ex)
            {
                if (ftpStream != null)
                    ftpStream.Close();
                if (outputStream != null)
                    outputStream.Close();
                if (response != null)
                    response.Close();
                if (File.Exists(FileName))
                    File.Delete(FileName);
                throw new Exception("FTP下载文件过程中发生错误:" + ex.Message);
            }
        }


        /// <summary> 
        /// 删除文件 
        /// </summary> 
        /// <param name="fileName"></param> 
        public void Delete(string fileName)
        {
            try
            {
                string uri = ftpURI + fileName;
                FtpWebRequest reqFTP;
                reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
                reqFTP.Timeout = timeOut;
                reqFTP.UsePassive = model;
                if (!anonymous)
                    reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
                reqFTP.KeepAlive = false;
                reqFTP.Method = WebRequestMethods.Ftp.DeleteFile;
                string result = String.Empty;
                FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
                long size = response.ContentLength;
                Stream datastream = response.GetResponseStream();
                StreamReader sr = new StreamReader(datastream);
                result = sr.ReadToEnd();
                sr.Close();
                datastream.Close();
                response.Close();
            }
            catch (Exception ex)
            {
                throw new Exception("FTP删除文件过程中发生错误:" + ex.Message);
            }
        }

        /// <summary> 
        /// 删除文件夹 
        /// </summary> 
        /// <param name="folderName"></param> 
        public void RemoveDirectory(string folderName)
        {
            try
            {
                string uri = ftpURI + folderName;
                FtpWebRequest reqFTP;
                reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
                reqFTP.Timeout = timeOut;
                reqFTP.UsePassive = model;
                if (!anonymous)
                    reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
                reqFTP.KeepAlive = false;
                reqFTP.Method = WebRequestMethods.Ftp.RemoveDirectory;



                string result = String.Empty;
                FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
                long size = response.ContentLength;
                Stream datastream = response.GetResponseStream();
                StreamReader sr = new StreamReader(datastream);
                result = sr.ReadToEnd();
                sr.Close();
                datastream.Close();
                response.Close();
            }
            catch (Exception ex)
            {
                throw new Exception("FTP删除文件夹过程中发生错误:" + ex.Message);
            }
        }

        /// <summary> 
        /// 获取当前目录下明细(包含文件和文件夹) 
        /// </summary> 
        /// <returns></returns> 
        public string[] GetFilesDetailList()
        {
            try
            {
                StringBuilder result = new StringBuilder();
                FtpWebRequest reqFTP;
                reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI));
                if (!anonymous)
                    reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
                reqFTP.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
                reqFTP.Timeout = timeOut;
                reqFTP.UsePassive = model;
                WebResponse response = reqFTP.GetResponse();
                StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.Default);
                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)
            {
                throw new Exception("FTP获取目录过程中发生错误:" + ex.Message);
            }
        }

        public string[] GetFileList(string mask)
        {
            return GetFileList("", mask);
        }
        public string[] GetFileList(string TopicDBCode, string mask)
        {
            return GetFileList(TopicDBCode, mask, "");
        }
        /// <summary>
        /// 获取当前目录下文件列表(仅文件) 
        /// </summary>
        /// <param name="TopicDBCode"></param>
        /// <param name="mask"></param>
        /// <param name="Uri">文件夹/</param>
        /// <returns></returns>
        public string[] GetFileList(string TopicDBCode, string mask, string Uri)
        {
            string[] downloadFiles;
            StringBuilder result = new StringBuilder();
            FtpWebRequest reqFTP;
            try
            {
                if (!string.IsNullOrEmpty(Uri))
                {
                    reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI + Uri));
                }
                else
                {
                    reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI));
                }
                reqFTP.Timeout = timeOut;
                reqFTP.UsePassive = model;
                reqFTP.UseBinary = true;
                if (!anonymous)
                    reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
                reqFTP.Method = WebRequestMethods.Ftp.ListDirectory;
                WebResponse response = reqFTP.GetResponse();
                StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.Default);
                string line = reader.ReadLine();
                while (line != null)
                {
                    if (mask.Trim() != string.Empty && mask.Trim() != "*.*")
                    {
                        int length = mask.IndexOf("*");
                        if (length < line.Length)
                        {
                            string mask_ = mask.Substring(0, length);
                            if (line.Substring(0, mask_.Length) == mask_)
                            {
                                result.Append(line);
                                result.Append("\n");
                            }
                        }
                    }
                    else
                    {
                        result.Append(line);
                        result.Append("\n");
                    }
                    line = reader.ReadLine();
                }
                string val = result.ToString();
                if (!string.IsNullOrEmpty(val))
                    result.Remove(val.LastIndexOf('\n'), 1);
                reader.Close();
                response.Close();
                val = result.ToString();
                if (!string.IsNullOrEmpty(val))
                    return result.ToString().Split('\n');
                else return null;
            }
            catch (Exception ex)
            {
                downloadFiles = null;
                if (ex.Message.Trim() != "远程服务器返回错误: (550) 文件不可用(例如,未找到文件,无法访问文件)。")
                {
                    throw new Exception("FTP获取目录失败:" + ex.Message);
                }
                return downloadFiles;
            }
        }

        /// <summary> 
        /// 获取当前目录下所有的文件夹列表(仅文件夹) 
        /// </summary> 
        /// <returns></returns> 
        public string[] GetDirectoryList()
        {
            string[] drectory = GetFilesDetailList();
            string m = string.Empty;
            foreach (string str in drectory)
            {
                int dirPos = str.IndexOf("<DIR>");
                if (dirPos > 0)
                {
                    /*判断 Windows 风格*/
                    m += str.Substring(dirPos + 5).Trim() + "\n";
                }
                else if (str.Trim().Substring(0, 1).ToUpper() == "D")
                {
                    /*判断 Unix 风格*/
                    string dir = str.Substring(54).Trim();
                    if (dir != "." && dir != "..")
                    {
                        m += dir + "\n";
                    }
                }
            }

            char[] n = new char[] { '\n' };
            return m.Split(n);
        }

        /// <summary> 
        /// 判断当前目录下指定的子目录是否存在 
        /// </summary> 
        /// <param name="RemoteDirectoryName">指定的目录名</param> 
        public bool DirectoryExist(string RemoteDirectoryName)
        {
            string[] dirList = GetDirectoryList();
            foreach (string str in dirList)
            {
                if (str.Trim() == RemoteDirectoryName.Trim())
                {
                    return true;
                }
            }
            return false;
        }

        /// <summary> 
        /// 判断当前目录下指定的文件是否存在 
        /// </summary> 
        /// <param name="RemoteFileName">远程文件名</param> 
        public bool FileExist(string RemoteFileName)
        {
            string[] fileList = GetFileList("*.*");
            if (fileList == null)
            {
                return false;
            }

            foreach (string str in fileList)
            {
                if (str.Trim() == RemoteFileName.Trim())
                {
                    return true;
                }
            }
            return false;
        }

        /// <summary> 
        /// 创建文件夹 
        /// </summary> 
        /// <param name="dirName"></param> 
        public void MakeDir(string dirName)
        {
            FtpWebRequest reqFTP;
            try
            {
                reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI + dirName));
                reqFTP.Timeout = timeOut;
                reqFTP.UsePassive = model;
                reqFTP.Method = WebRequestMethods.Ftp.MakeDirectory;
                reqFTP.UseBinary = true;
                if (!anonymous)
                    reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
                FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
                Stream ftpStream = response.GetResponseStream();

                ftpStream.Close();
                response.Close();
            }
            catch (Exception ex)
            {
                throw new Exception("FTP创建文件夹过程中发生错误:" + ex.Message);
            }
        }

        /// <summary> 
        /// 获取指定文件大小 
        /// </summary> 
        /// <param name="filename"></param> 
        /// <returns></returns> 
        public long GetFileSize(string filename)
        {
            FtpWebRequest reqFTP;
            long fileSize = 0;
            try
            {
                reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI + filename));
                reqFTP.Timeout = timeOut;
                reqFTP.UsePassive = model;
                reqFTP.Method = WebRequestMethods.Ftp.GetFileSize;
                reqFTP.UseBinary = true;
                if (!anonymous)
                    reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
                FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
                Stream ftpStream = response.GetResponseStream();
                fileSize = response.ContentLength;

                ftpStream.Close();
                response.Close();
            }
            catch (Exception ex)
            {
                throw new Exception("FTP获取文件大小失败:" + ex.Message);
            }
            return fileSize;
        }

        /// <summary> 
        /// 改名 
        /// </summary> 
        /// <param name="currentFilename"></param> 
        /// <param name="newFilename"></param> 
        public void ReName(string currentFilename, string newFilename)
        {
            FtpWebRequest reqFTP;
            try
            {
                reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI + currentFilename));
                reqFTP.Timeout = timeOut;
                reqFTP.UsePassive = model;
                reqFTP.Method = WebRequestMethods.Ftp.Rename;
                reqFTP.RenameTo = newFilename;
                reqFTP.UseBinary = true;
                if (!anonymous)
                    reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
                FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
                Stream ftpStream = response.GetResponseStream();

                ftpStream.Close();
                response.Close();
            }
            catch (Exception ex)
            {
                throw new Exception("FTP文件改名失败:" + ex.Message);
            }
        }

        /// <summary> 
        /// 移动文件 
        /// </summary> 
        /// <param name="currentFilename"></param> 
        /// <param name="newFilename"></param> 
        public void MovieFile(string currentFilename, string newDirectory)
        {
            ReName(currentFilename, newDirectory);
        }

        /// <summary> 
        /// 切换当前目录 
        /// </summary> 
        /// <param name="DirectoryName"></param> 
        /// <param name="IsRoot">true 绝对路径   false 相对路径</param> 
        public void GotoDirectory(string DirectoryName, bool IsRoot)
        {
            if (IsRoot)
            {
                ftpRemotePath = DirectoryName;
            }
            else
            {
                ftpRemotePath += DirectoryName + "/";
            }
            ftpURI = "ftp://" + ftpServerIP + "/" + ftpRemotePath + "/";
        }

        /// <summary> 
        /// 删除目录 
        /// </summary> 
        /// <param name="ftpServerIP">FTP 主机地址</param> 
        /// <param name="folderToDelete">FTP 用户名</param> 
        /// <param name="ftpUserID">FTP 用户名</param> 
        /// <param name="ftpPassword">FTP 密码</param> 
        public static void DeleteOrderDirectory(string ftpServerIP, string folderToDelete, string ftpUserID, string ftpPassword, string FtpPort)
        {
            try
            {
                if (!string.IsNullOrEmpty(ftpServerIP) && !string.IsNullOrEmpty(folderToDelete) && !string.IsNullOrEmpty(ftpUserID) && !string.IsNullOrEmpty(ftpPassword))
                {
                    FtpWeb fw = new FtpWeb(ftpServerIP, folderToDelete, ftpUserID, ftpPassword, FtpPort);
                    //进入订单目录 
                    fw.GotoDirectory(folderToDelete, true);
                    //获取规格目录 
                    string[] folders = fw.GetDirectoryList();
                    foreach (string folder in folders)
                    {
                        if (!string.IsNullOrEmpty(folder) || folder != "")
                        {
                            //进入订单目录 
                            string subFolder = folderToDelete + "/" + folder;
                            fw.GotoDirectory(subFolder, true);
                            //获取文件列表 
                            string[] files = fw.GetFileList("*.*");
                            if (files != null)
                            {
                                //删除文件 
                                foreach (string file in files)
                                {
                                    fw.Delete(file);
                                }
                            }
                            //删除冲印规格文件夹 
                            fw.GotoDirectory(folderToDelete, true);
                            fw.RemoveDirectory(folder);
                        }
                    }

                    //删除订单文件夹 
                    string parentFolder = folderToDelete.Remove(folderToDelete.LastIndexOf('/'));
                    string orderFolder = folderToDelete.Substring(folderToDelete.LastIndexOf('/') + 1);
                    fw.GotoDirectory(parentFolder, true);
                    fw.RemoveDirectory(orderFolder);
                }
                else
                {
                    throw new Exception("FTP路径不能为空!");
                }
            }
            catch (Exception ex)
            {
                throw new Exception("FTP删除目录时发生错误,错误信息为:" + ex.Message);
            }
        }
    }
posted @ 2016-06-15 11:08  灬花儿灬  阅读(9965)  评论(0编辑  收藏  举报