ftp文件下载公共类

最近做了一个关于ftp文件上传下载的课题,现做一下代码分享

ftp操作公用类

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Net;

/// <summary>
/// Version:2.14.11.1
/// Time:2014/11/05
/// Author:lover6796
/// Content:Ftp操作公共类
/// </summary>
public class FtpClass
{

    public static string ftpServerIP = System.Configuration.ConfigurationManager.AppSettings["FtpIP"];
    public static string ftpUserID = System.Configuration.ConfigurationManager.AppSettings["FtpUserName"].ToString();
    public static string ftpPassword = System.Configuration.ConfigurationManager.AppSettings["FtpPassWord"];
    public string ftpURI;
    public static string ftpRemotePath = System.Configuration.ConfigurationManager.AppSettings["ftpRemotePath"];
    /// <summary>
    /// 连接FTP
    /// </summary>
    /// <param name="FtpServerIP">FTP连接地址</param>
    /// <param name="FtpRemotePath">指定FTP连接成功后的当前目录, 如果不指定即默认为根目录</param>
    /// <param name="FtpUserID">用户名</param>
    /// <param name="FtpPassword">密码</param>
    public FtpClass(string FtpServerIP, string FtpRemotePath, string FtpUserID, string FtpPassword)
    {
        ftpServerIP = FtpServerIP;
        ftpRemotePath = FtpRemotePath;
        ftpUserID = FtpUserID;
        ftpPassword = FtpPassword;
        // ftpURI = "ftp://" + ftpServerIP + "/" + ftpRemotePath + "/";
        ftpURI = "ftp://" + ftpServerIP + "/";
    }
    /// <summary>
    /// 上传
    /// </summary>
    /// <param name="filename"></param>
    public void FtpUpload(string filename)
    {
        FileInfo fileInf = new FileInfo(filename);
        string uri = ftpURI + fileInf.Name;
        FtpWebRequest reqFTP;
        reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
        reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
        reqFTP.KeepAlive = false;
        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 (ex);
        }
    }
    /// <summary>
    /// 下载
    /// </summary>
    /// <param name="filePath"></param>
    /// <param name="fileName"></param>
    public void FtpDownload(string filePath, string fileName)
    {

        FtpWebRequest reqFTP;
        FileStream outputStream = new FileStream(filePath + "\\" + fileName, FileMode.Create);
        reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI + fileName));
        reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
        reqFTP.UseBinary = true;
        reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
        FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();

        Stream ftpStream = response.GetResponseStream();
        long cl = response.ContentLength;
        int bufferSize = 2048;
        int readCount;
        byte[] buffer = new byte[bufferSize];
        try
        {
            readCount = ftpStream.Read(buffer, 0, bufferSize);
            while (readCount > 0)
            {
                outputStream.Write(buffer, 0, readCount);
                readCount = ftpStream.Read(buffer, 0, bufferSize);
            }
        }
        catch (Exception ex)
        {
            throw (ex);
        }
        ftpStream.Close();
        outputStream.Close();
        response.Close();
    }

    /// <summary>
    /// 判断服务器上对应的文件是否存在
    /// </summary>
    /// <param name="RemoteFileName"></param>
    /// <returns></returns>
    public bool FileExist(string RemoteFileName)
    {
        string[] fileList = GetFileList("*.*");
        if (fileList != null)
        {
            foreach (string str in fileList)
            {
                if (str.Trim() == RemoteFileName.Trim())
                {
                    return true;
                }
            }
        }
        return false;
    }

    /// <summary>
    /// 获取ftp服务器上的文件列表
    /// </summary>
    /// <param name="path"></param>
    /// <param name="WRMethods"></param>
    /// <returns></returns>
    private string[] GetFileList(string path, string WRMethods)//上面的代码示例了如何从ftp服务器上获得文件列表
    {
        string[] downloadFiles;
        System.Text.StringBuilder result = new System.Text.StringBuilder();
        FtpWebRequest reqFTP;
        try
        {
             reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(path));            // 指定数据传输类型
            reqFTP.UseBinary = true;
            reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);   // ftp用户名和密码
            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();
            }
            result.Remove(result.ToString().LastIndexOf(‘\n‘), 1);
            reader.Close();
            response.Close();
            downloadFiles= result.ToString().Split(‘\n‘);
        }
        catch (Exception ex)
        {
            downloadFiles = null;
            throw (ex);
        }
        return downloadFiles;
    }

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

}
 调用方法

FtpClass ftp = new FtpClass(FtpClass.ftpServerIP, FtpClass.ftpRemotePath, FtpClass.ftpUserID, FtpClass.ftpPassword);
                            if (ftp.FileExist(pdfname))
                            {
                                ftp.FtpDownload(path + "\\FTtemp", pdfname);
                                                                   Response.ContentType = "application/zip";
                                    Response.AddHeader("Content-Disposition", "attachment;filename=" + pdfname);
                                    string filename = path + "\\FTtemp\\" + pdfname;
                                    Response.WriteFile(filename);

}

配置文件

  <appSettings>
    <!--ftp信息配置   -->
    <add key="FtpIP" value="**.**.**.**:**"/>
    <add key="FtpUserName" value="ftp"/>
    <add key="FtpPassWord" value="ftp"/>
    <add key ="ftpRemotePath" value=""/>
  </appSettings>
				
时间: 2024-08-02 15:18:35

ftp文件下载公共类的相关文章

C# Http文件下载公共类(支持断点续传)

1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.IO; 6 using System.Net; 7 8 namespace XcDownLoadFile 9 { 10 public class DownLoadFile 11 { 12 /// 13 /// 下载文件方法 14 /// 15 /// 文件保存路径和文件名 16 /

ftp中ftpClient类的API

org.apache.commons.NET.ftp  Class FTPClient类FTPClient java.lang.Object java.lang.Object继承 org.apache.commons.net.SocketClient org.apache.commons.net.SocketClient org.apache.commons.net.ftp.FTP org.apache.commons.net.ftp.FTP org.apache.commons.net.ftp

C# 实现模拟登录功能,实现公共类分享。

前言 最近在研究模拟登录的各种方法, 主要想要实现的两个功能是: 1.点击按钮可以直接跳转并登录到某一个系统中. 2.抓取某一个系统中某一个页面中的特定数据. 为此在网上查了许多的资料,首先了解到自身对http协议基础知识的欠缺,初步了解后,明白想要实现模拟登录首先要学会抓包这一项基本的技能,关于抓包这里就不详细介绍了,向大家推荐一款软件fiddler,一款不错的抓包软件. 首先客户端向服务端请求无非两种类型get或post,所以我们要了解在登录某一个系统时post的地址,以及需要post的参数

C# 调用API接口处理公共类 自带JSON实体互转类

using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Net.Security; using System.Security.Cryptography.X509Certificates; using System.Text; using System.Threading.Tasks; using System.Web; n

Android公共库——图片缓存 网络缓存 下拉及底部更多ListView 公共类

Android公共库--图片缓存 网络缓存 下拉及底部更多ListView 公共类 转载自http://www.trinea.cn/android/android-common-lib/ 介绍总结的一些android公共库,包含缓存(图片缓存.预取缓存.网络缓存).公共View(下拉及底部加载更多ListView.底部加载更多ScrollView.滑动一页Gallery).及Android常用工具类(网络.下载.shell.文件.json等等). TrineaAndroidCommon已开源,地

CodeSmith公共类维护

CodeSmith在使用过程中,我们经常会出现同一个方法在不同的页面调用,如果我们在每个页面都写一个这样的方法,那么代码量非常大,同时如果以后需要修改也要在每个页面分别去修改,这无疑是劳命伤财,如果能够有更好的方法那么又何乐而不为呢.下面提供两种方式: 方法一: 1.创建公共类comm.cs,类里面的内容如下: public string getData() { return "abc"; } 2.调用的cst文件内容如下: <%@ CodeTemplate Language=&

MVC 公共类App_Code不识别

.Net MVC需要写公共类的时候 右击添加 App_Code 文件夹,新建类—>右击类—>属性,生成操作 —>选择 —>编译 .net MVC项目本身是个应用程序,所以其实不需要专门起名为App_Code文件夹放入公共类,只要在项目下建类文件在那都可以,只要改成可编译的就行. 而最传统的asp.net文件系统App_Code文件夹是专门放类文件的,你放在其它地方反而不认,这两个的区别是项目的区别.

Java ClassLoader基础及加载不同依赖 Jar 中的公共类

转载自:最新内容及最清晰格式请见 http://www.trinea.cn/android/java-loader-common-class/ 本文主要介绍 ClassLoader 的基础知识,ClassLoader 如何动态加载 Jar,ClassLoader 隔离问题及如何加载不同 Jar 中的公共类. 本文工程开源地址见:Java Dynamic Load [email protected],Clone 以后直接以 Java Application去运行 java-dynamic-load

java判断一个类是否公共类

Modifier.isPublic([类].getModifiers()) Modifier.isAbstract([类].getModifiers()) java判断一个类是否公共类,布布扣,bubuko.com