最近做了一个关于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>