zoukankan      html  css  js  c++  java
  • ASP.net:Ftp操作FtpWebRequest

    项目用到就贴了下来:

    using System;
    using System.Collections.Generic;
    using System.Text;
    using System.IO;
    using System.Net;
    using System.Web;
    using SSI.Application.Log;
    using System.Configuration;

    namespace Tctax.External.Web.Upload
    {
        public class FtpClass
        {
            string ftpServerIP;
            string ftpUserID;
            string ftpPassword;
            FtpWebRequest reqFTP;

            /// <summary>
            /// 连接ftp
            /// </summary>
            /// <param name="path"></param>
            private void Connect(String path)
            {
                // 根据uri创建FtpWebRequest对象
                reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(path));

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

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

            /// <summary>
            /// 获取一个Ftp操作对象:ServerIP、UserID、Password 已初始化
            /// </summary>
            public FtpClass()
            {
                FtpSection ftpSetting = ConfigurationManager.GetSection("ftpinfo") as FtpSection;
                this.ftpServerIP = ftpSetting.FtpServer;
                this.ftpUserID = ftpSetting.User;
                this.ftpPassword = ftpSetting.PassWord;
            }

            /// <summary>
            /// 获取一个Ftp操作对象
            /// </summary>
            /// <param name="ftpServerIP"></param>
            /// <param name="ftpUserID"></param>
            /// <param name="ftpPassword"></param>
            public FtpClass(string ftpServerIP, string ftpUserID, string ftpPassword)
            {
                this.ftpServerIP = ftpServerIP;
                this.ftpUserID = ftpUserID;
                this.ftpPassword = ftpPassword;
            }

            //都调用这个
            private string[] GetFileList(string path, string WRMethods)//上面的代码示例了如何从ftp服务器上获得文件列表
            {
                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();
                    }

                    // to remove the trailing '\n'
                    result.Remove(result.ToString().LastIndexOf("\n", StringComparison.OrdinalIgnoreCase), 1);
                    reader.Close();
                    response.Close();
                    return result.ToString().Split('\n');
                }

                catch
                {
                    downloadFiles = null;
                    return downloadFiles;
                    throw;
                }
            }

            /// <summary>
            /// //上面的代码示例了如何从ftp服务器上获得文件列表
            /// </summary>
            /// <param name="path"></param>
            /// <returns></returns>
            public string[] GetFileList(string path)
            {
                return GetFileList(ftpServerIP + "/" + path, WebRequestMethods.Ftp.ListDirectory);
            }

            /// <summary>
            /// 判断文件是否存在
            /// </summary>
            /// <param name="fileName"></param>
            /// <returns></returns>
            public bool ValidateFileExist(string fileName)
            {
                string[] allFiles = GetFileList(ftpServerIP, WebRequestMethods.Ftp.ListDirectory);
                if (allFiles == null)
                {
                    return false;
                }
                string result = Array.Find(allFiles, delegate(String list)
                {
                    return list.Equals(fileName) ? true : false;
                });
                if (!string.IsNullOrEmpty(result))
                {
                    return true;
                }
                else
                    return false;
            }

            /// <summary>
            /// //上面的代码示例了如何从ftp服务器上获得文件列表
            /// </summary>
            /// <returns></returns>
            public string[] GetFileList()
            {
                return GetFileList(ftpServerIP + "/", WebRequestMethods.Ftp.ListDirectory);
            }
            public bool Upload(Stream stream, string filename)
            {
                string uri = ftpServerIP + "/" + filename;
                Connect(uri);//连接         
                // 默认为true,连接不会被关闭
                // 在一个命令之后被执行
                reqFTP.KeepAlive = false;
                // 指定执行什么命令
                reqFTP.Method = WebRequestMethods.Ftp.UploadFile;
                reqFTP.ContentLength = stream.Length;
                int buffLength = 2048;
                byte[] buff = new byte[buffLength];
                int contentLen;

                try
                {
                    Stream strm = reqFTP.GetRequestStream();
                    contentLen = stream.Read(buff, 0, buffLength);
                    while (contentLen != 0)
                    {
                        strm.Write(buff, 0, contentLen);
                        contentLen = stream.Read(buff, 0, buffLength);
                    }
                    strm.Close();
                    stream.Close();
                    return true;
                }
                catch (Exception ex)
                {
                    MyLogManager.LogError("UploadFileFtp", "Upload Error" + ex.Message, new object[] { });
                }
                return false;
            }
            /// <summary>
            ///  //上面的代码实现了从ftp服务器上载文件的功能
            /// </summary>
            /// <param name="filename"></param>
            public void Upload(string filename)
            {
                FileInfo fileInf = new FileInfo(filename);
                string uri = ftpServerIP + "/" + fileInf.Name;
                Connect(uri);//连接         
                // 默认为true,连接不会被关闭
                // 在一个命令之后被执行
                reqFTP.KeepAlive = false;
                // 指定执行什么命令
                reqFTP.Method = WebRequestMethods.Ftp.UploadFile;
                // 上传文件时通知服务器文件的大小
                reqFTP.ContentLength = fileInf.Length;
                // 缓冲大小设置为kb
                int buffLength = 2048;
                byte[] buff = new byte[buffLength];
                int contentLen;
                // 打开一个文件流(System.IO.FileStream) 去读上传的文件
                FileStream fs = fileInf.OpenRead();
                try
                {
                    // 把上传的文件写入流
                    Stream strm = reqFTP.GetRequestStream();
                    // 每次读文件流的kb
                    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 (Exception ex)
                {
                    MyLogManager.LogError("UploadFileFtp", "Upload Error" + ex.Message, new object[] {ex });
                }

            }

            /// <summary>
            /// ////上面的代码实现了从ftp服务器下载文件的功能
            /// </summary>
            /// <param name="filePath"></param>
            /// <param name="fileName"></param>
            /// <param name="errorinfo"></param>
            /// <returns></returns>
            public bool Download(string filePath, string fileName, out string errorinfo)


            {
                try
                {
                    String onlyFileName = Path.GetFileName(fileName);
                    string newFileName = filePath + "\\" + onlyFileName;
                    if (File.Exists(newFileName))
                    {
                        errorinfo = string.Format("本地文件{0}已存在,无法下载", newFileName);
                        return false;
                    }
                    string url = ftpServerIP + "/" + fileName;
                    Connect(url);//连接 
                    reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
                    FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
                    Stream ftpStream = response.GetResponseStream();
                    int bufferSize = 2048;
                    int readCount;
                    byte[] buffer = new byte[bufferSize];
                    readCount = ftpStream.Read(buffer, 0, bufferSize);
                    FileStream outputStream = new FileStream(newFileName, FileMode.Create);
                    while (readCount > 0)
                    {
                        outputStream.Write(buffer, 0, readCount);
                        readCount = ftpStream.Read(buffer, 0, bufferSize);
                    }
                    ftpStream.Close();
                    outputStream.Close();
                    response.Close();
                    errorinfo = "";
                    return true;
                }
                catch (Exception ex)
                {
                    errorinfo = string.Format("因{0},无法下载", ex.Message);
                    return false;
                }

            }

            /// <summary>
            /// //删除文件
            /// </summary>
            /// <param name="fileName"></param>
            public bool DeleteFileName(string fileName)
            {
                try
                {
                    string uri = ftpServerIP + "/" + fileName;
                    Connect(uri);//连接         
                    // 默认为true,连接不会被关闭
                    // 在一个命令之后被执行
                    reqFTP.KeepAlive = false;
                    // 指定执行什么命令
                    reqFTP.Method = WebRequestMethods.Ftp.DeleteFile;
                    FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
                    response.Close();
                    return true;
                }
                catch (Exception ex)
                {
                    MyLogManager.LogError("DeleteFileFtp", "Delete Error" + ex.Message, new object[] { ex });
                }
                return false;
            }

            /// <summary>
            /// //创建目录
            /// </summary>
            /// <param name="dirName"></param>
            public void MakeFtpDir(string dirName)
            {
                try
                {
                    string uri = ftpServerIP + "/" + dirName;
                    Connect(uri);//连接      
                    reqFTP.Method = WebRequestMethods.Ftp.MakeDirectory;
                    FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
                    response.Close();
                }
                catch (Exception ex)
                {
                    MyLogManager.LogError("MakeFtpDir", "Make Ftp Dir Error" + ex.Message, new object[] { ex });
                }
            }

            /// <summary>
            /// //删除目录
            /// </summary>
            /// <param name="dirName"></param>
            public void DelDir(string dirName)
            {
                try
                {
                    string uri = ftpServerIP + "/" + dirName;
                    Connect(uri);//连接      
                    reqFTP.Method = WebRequestMethods.Ftp.RemoveDirectory;
                    FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
                    response.Close();
                }
                catch (Exception ex)
                {
                    MyLogManager.LogError("DelDir", "Del Ftp Dir Error" + ex.Message, new object[] { ex });
                }
            }

            /// <summary>
            /// //获得文件大小
            /// </summary>
            /// <param name="filename"></param>
            /// <returns></returns>
            public long GetFileSize(string filename)
            {
                long fileSize = 0;
                try
                {
                    FileInfo fileInf = new FileInfo(filename);
                    string uri = ftpServerIP + "/" + fileInf.Name;
                    Connect(uri);//连接      
                    reqFTP.Method = WebRequestMethods.Ftp.GetFileSize;
                    FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
                    fileSize = response.ContentLength;
                    response.Close();
                }
                catch (Exception ex)
                {
                    MyLogManager.LogError("GetFileSize", "GetFileSize Error" + ex.Message, new object[] { ex });

                }
                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 = 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 ex)
                {
                    MyLogManager.LogError("Rename", "Rename Error" + ex.Message, new object[] { ex });
                }
            }

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

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

            /// <summary>
            /// Gets the FTP server IP.
            /// </summary>
            /// <returns></returns>
            public string GetFtpServerIP()
            {
                return ftpServerIP;
            }
        }
    }

    映射处理:

    using System;
    using System.Collections.Generic;
    using System.Text;
    using System.IO;
    using System.Net;
    using System.Web;
    using SSI.Application.Log;
    using System.Configuration;

    namespace Tctax.External.Web.Upload
    {
        public static class FtpUpload
        {
            static FtpClass ftp = new FtpClass();
            //static FtpClass ftp = new FtpClass("ftp://192.168.98.5/", "tctax", "tc0520090126!"); //ftp上传固定地址

            private static FtpSection ftpSetting = ConfigurationManager.GetSection("ftpinfo") as FtpSection;
            public static bool DeleteFileName(string fileName)
            {
                return ftp.DeleteFileName(fileName);
            }

            public static bool UploadFileToFtp(out string filename, HttpPostedFile filepath)
            {
                filename = Guid.NewGuid().ToString() + filepath.FileName.Substring(filepath.FileName.LastIndexOf(".", StringComparison.OrdinalIgnoreCase));
                return ftp.Upload(filepath.InputStream,filename);
            }
            public static FtpSection FtpSection
            {
                get
                {
                    return ftpSetting;
                }
            }
            public static bool ValidateFileExist(string fileName)
            {
                return ftp.ValidateFileExist(fileName);
            }

            public static bool UploadFileToFtp(Stream stream, string filename)
            {
                return ftp.Upload(stream, filename);
            }

            public static string GetFtpServerIP()
            {
                return ftp.GetFtpServerIP();
            }
        }


        public class FtpSection : ConfigurationSection
        {
            public FtpSection()
            {
                //
                // TODO: 在此处添加构造函数逻辑
                //
            }

            [ConfigurationProperty("ftpServer", DefaultValue = "ftp://", IsRequired = true)]
            public string FtpServer
            {
                get { return (string)this["ftpServer"]; }
                set { this["ftpServer"] = value; }
            }

            [ConfigurationProperty("ftpUser", DefaultValue = "test", IsRequired = true)]
            public string User
            {
                get { return (string)this["ftpUser"]; }
                set { this["ftpUser"] = value; }
            }

            [ConfigurationProperty("ftpPwd", DefaultValue = "test", IsRequired = true)]
            public string PassWord
            {
                get { return (string)this["ftpPwd"]; }
                set { this["ftpPwd"] = value; }
            }

            [ConfigurationProperty("urlMapping", DefaultValue = "", IsRequired = true)]
            public string URL
            {
                get { return (string)this["urlMapping"]; }
                set { this["urlMapping"] = value; }
            }
        }
    }

    Web.config配置:

    <connectionStrings/>
     <!--FTP文件上传设置!-->
     <ftpinfo ftpServer="ftp://10.10.2.202/" ftpUser="test" ftpPwd="1qaz@wsx" urlMapping="http://10.10.2.202:2009/ftpFile/"/>

    滄海一粟
  • 相关阅读:
    [C++] 习题 2.18 倒序查找字串
    [C++] 二叉树计算文件单词数
    [C++] 例题 2.7.1 用栈实现简易计算器
    [C++] 非递归实现前中后序遍历二叉树
    [C++] 习题 2.15 实现简单环形队列
    数据结构、算法及应用
    [C++] 习题 2.14 用队列实现桶排序
    svn add 所有文件的命令
    解决Error opening terminal: xterm.的错误
    linux下删除项目中所有.svn的命令
  • 原文地址:https://www.cnblogs.com/zhanghaichang/p/1967321.html
Copyright © 2011-2022 走看看