一些参考案例下面是一些常用的ftp操作文件的方法
案列1
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Net;
using System.Windows.Forms;
using System.Globalization;
namespace FtpTest1
{
public class FtpWeb
{
string ftpServerIP;
string ftpRemotePath;
string ftpUserID;
string ftpPassword;
string ftpURI;
///
/// FTP连接地址
/// 指定FTP连接成功后的当前目录, 如果不指定即默认为根目录
/// 用户名
/// 密码
public FtpWeb(string FtpServerIP, string FtpRemotePath, string FtpUserID, string FtpPassword)
{
ftpServerIP = FtpServerIP;
ftpRemotePath = FtpRemotePath;
ftpUserID = FtpUserID;
ftpPassword = FtpPassword;
ftpURI = "ftp://" + ftpServerIP + "/" + ftpRemotePath + "/";
}
///
///
public void Upload(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 = ;
byte[] buff = new byte[buffLength];
int contentLen;
FileStream fs = fileInf.OpenRead();
try
{
Stream strm = reqFTP.GetRequestStream();
contentLen = fs.Read(buff, , buffLength);
while (contentLen != )
{
strm.Write(buff, , contentLen);
contentLen = fs.Read(buff, , buffLength);
}
strm.Close();
fs.Close();
}
catch (Exception ex)
{
Insert_Standard_ErrorLog.Insert("FtpWeb", "Upload Error --> " + ex.Message);
}
}
///
///
///
public void Download(string filePath, string fileName)
{
FtpWebRequest reqFTP;
try
{
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 = ;
int readCount;
byte[] buffer = new byte[bufferSize];
readCount = ftpStream.Read(buffer, , bufferSize);
while (readCount > )
{
outputStream.Write(buffer, , readCount);
readCount = ftpStream.Read(buffer, , bufferSize);
}
ftpStream.Close();
outputStream.Close();
response.Close();
}
catch (Exception ex)
{
Insert_Standard_ErrorLog.Insert("FtpWeb", "Download Error --> " + ex.Message);
}
}
///
///
public void Delete(string fileName)
{
try
{
string uri = ftpURI + fileName;
FtpWebRequest reqFTP;
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
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)
{
Insert_Standard_ErrorLog.Insert("FtpWeb", "Delete Error --> " + ex.Message + " 文件名:" + fileName);
}
}
///
///
public string[] GetFilesDetailList()
{
string[] downloadFiles;
try
{
StringBuilder result = new StringBuilder();
FtpWebRequest ftp;
ftp = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI));
ftp.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
ftp.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
WebResponse response = ftp.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream());
string line = reader.ReadLine();
line = reader.ReadLine();
line = reader.ReadLine();
while (line != null)
{
result.Append(line);
result.Append("/n");
line = reader.ReadLine();
}
result.Remove(result.ToString().LastIndexOf("/n"), );
reader.Close();
response.Close();
return result.ToString().Split('/n');
}
catch (Exception ex)
{
downloadFiles = null;
Insert_Standard_ErrorLog.Insert("FtpWeb", "GetFilesDetailList Error --> " + ex.Message);
return downloadFiles;
}
}
///
///
private string[] GetAllList(string url,string userid,string password)
{
List
FtpWebRequest req = (FtpWebRequest)WebRequest.Create(new Uri(url));
req.Credentials = new NetworkCredential(userid, password);
req.Method = WebRequestMethods.Ftp.ListDirectory;
req.UseBinary = true;
req.UsePassive = true;
try
{
using (FtpWebResponse res = (FtpWebResponse)req.GetResponse())
{
using (StreamReader sr = new StreamReader(res.GetResponseStream()))
{
string s;
while ((s = sr.ReadLine()) != null)
{
list.Add(s);
}
}
}
}
catch (Exception ex)
{
throw (ex);
}
return list.ToArray();
}
///
///
public string[] GetFileList(string url,string userid,string password)
{
StringBuilder result = new StringBuilder();
FtpWebRequest reqFTP;
try
{
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(url));
reqFTP.UseBinary = true;
reqFTP.Credentials = new NetworkCredential(userid, password);
reqFTP.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
WebResponse response = reqFTP.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream());
string line = reader.ReadLine();
while (line != null)
{
if (line.IndexOf("<DIR>")==-)
{
result.Append(Regex.Match(line, @"\[/S\]+ \[/S\]+", RegexOptions.IgnoreCase).Value.Split(' ')\[\]);
result.Append("/n");
}
line = reader.ReadLine();
}
result.Remove(result.ToString().LastIndexOf('/n'), );
reader.Close();
response.Close();
}
catch (Exception ex)
{
throw (ex);
}
return result.ToString().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("\*.\*");
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
{
// dirName = name of the directory to create.
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI + dirName));
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();
}
catch (Exception ex)
{
Insert\_Standard\_ErrorLog.Insert("FtpWeb", "MakeDir Error --> " + ex.Message);
}
}
/// <summary>
/// 获取指定文件大小
/// </summary>
/// <param name="filename"></param>
/// <returns></returns>
public long GetFileSize(string filename)
{
FtpWebRequest reqFTP;
long fileSize = ;
try
{
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI + filename));
reqFTP.Method = WebRequestMethods.Ftp.GetFileSize;
reqFTP.UseBinary = true;
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)
{
Insert\_Standard\_ErrorLog.Insert("FtpWeb", "GetFileSize Error --> " + 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.Method = WebRequestMethods.Ftp.Rename;
reqFTP.RenameTo = newFilename;
reqFTP.UseBinary = true;
reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
Stream ftpStream = response.GetResponseStream();
ftpStream.Close();
response.Close();
}
catch (Exception ex)
{
Insert\_Standard\_ErrorLog.Insert("FtpWeb", "ReName Error --> " + 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 + "/";
}
}
案列2
、
public class Helper
{
private string requestUriString = string.Empty;
private string userName = string.Empty;
private string password = string.Empty;
private FtpWebRequest request;
private FtpWebResponse response;
public Helper()
{
}
/// <summary>
/// 构造函数
/// </summary>
/// <param name="RequestUriString">登陆IP</param>
/// <param name="UserName">用户名</param>
/// <param name="Password">密码</param>
public Helper(string RequestUriString, string UserName, string Password)
{
this.requestUriString = "ftp://" + RequestUriString + "/";
this.userName = UserName;
this.password = Password;
}
/// <summary>
/// 创建FtpWebRequest
/// </summary>
/// <param name="uriString">FTP路径</param>
/// <param name="method">FTP方法</param>
private void OpenRequest(string uriString, string method)
{
try
{
this.request = WebRequest.Create(new Uri(this.requestUriString + uriString)) as FtpWebRequest;
this.request.Credentials = new NetworkCredential(userName, password);
this.request.UseBinary = true;
this.request.Method = method;
}
catch
{
}
}
/// <summary>
/// 返回FtpWebResponse
/// </summary>
/// <param name="uriString">FTP路径</param>
/// <param name="method">FTP方法</param>
private void OpenResponse(string uriString, string method)
{
try
{
this.OpenRequest(uriString, method);
this.response = this.request.GetResponse() as FtpWebResponse;
}
catch
{
}
}
/// <summary>
/// 创建目录
/// </summary>
/// <param name="directoryPath">要创建的目录名称</param>
public void MakeDirectory(string directoryPath)
{
this.OpenResponse(directoryPath, WebRequestMethods.Ftp.MakeDirectory);
}
/// <summary>
/// 删除目录
/// </summary>
/// <param name="directoryPath">要删除的目录名称</param>
public void RemoveDirectory(string directoryPath)
{
this.OpenResponse(directoryPath, WebRequestMethods.Ftp.RemoveDirectory);
}
/// <summary>
/// 重命名文件
/// </summary>
/// <param name="originalFileName">原文件名</param>
/// <param name="newFileName">新文件名</param>
public void Rename(string originalFileName, string newFileName)
{
this.OpenResponse(originalFileName, WebRequestMethods.Ftp.Rename);
this.request.RenameTo = newFileName;
this.response = this.request.GetResponse() as FtpWebResponse;
}
/// <summary>
/// 上传文件到服务器
/// </summary>
/// <param name="localFullPath">要上传的本地文件全路径</param>
public void UploadFile(string localFullPath)
{
this.UploadFile(localFullPath, false);
}
/// <summary>
/// 上传文件到服务器
/// </summary>
/// <param name="localFullPath">要上传的本地文件全路径</param>
/// <param name="overWriteFile">是否要重写服务器上的文件</param>
public void UploadFile(string localFullPath, bool overWriteFile)
{
this.UploadFile(localFullPath, Path.GetFileName(localFullPath), overWriteFile);
}
/// <summary>
/// 上传文件到服务器
/// /// </summary>
/// <param name="localFullPath">要上传的本地文件全路径</param>
/// <param name="remoteFileName">上传后文件重命名为</param>
public void UploadFile(string localFullPath, string remoteFileName)
{
this.UploadFile(localFullPath, remoteFileName, false);
}
/// <summary>
/// 上传文件到服务器
/// </summary>
/// <param name="localFullPath">要上传的本地文件全路径</param>
/// <param name="remoteFileName">上传后文件重命名为</param>
/// <param name="overWriteFile">是否要重写服务器上的文件</param>
public void UploadFile(string localFullPath, string remoteFileName, bool overWriteFile)
{
byte\[\] fileBytes = null;
using (FileStream fileStream = new FileStream(localFullPath, FileMode.Open, FileAccess.Read))
{
fileBytes = new byte\[fileStream.Length\];
fileStream.Read(fileBytes, , (Int32)fileStream.Length);
}
this.UploadFile(fileBytes, remoteFileName, overWriteFile);
}
/// <summary>
/// 上传文件到服务器
/// </summary>
/// <param name="fileBytes">上传文件的字节流</param>
/// <param name="remoteFileName">上传后文件重命名为</param>
public void UploadFile(byte\[\] fileBytes, string remoteFileName)
{
this.UploadFile(fileBytes, remoteFileName, false);
}
/// <summary>
/// 上传文件到服务器
/// </summary>
/// <param name="fileBytes">上传文件的字节流</param>
/// <param name="remoteFileName">上传后文件重命名为</param>
/// <param name="overWriteFile">是否要重写服务器上的文件</param>
public void UploadFile(byte\[\] fileBytes, string remoteFileName, bool overWriteFile)
{
this.OpenResponse(overWriteFile ? remoteFileName : Gadget.ReturnFileNameWithCurrentDate(remoteFileName),
WebRequestMethods.Ftp.UploadFile);
using (Stream stream = this.request.GetRequestStream())
{
using (MemoryStream memoryStream = new MemoryStream(fileBytes))
{
byte\[\] buffer = new byte\[Constant.FTP.LenOfBuffer\];
int bytesRead = ;
int totalRead = ;
while (true)
{
bytesRead = memoryStream.Read(buffer, , buffer.Length);
if (bytesRead == )
{
break;
}
totalRead += bytesRead;
stream.Write(buffer, , bytesRead);
}
}
this.response = this.request.GetResponse() as FtpWebResponse;
}
}
/// <summary>
/// 下载服务器文件到本地
/// </summary>
/// <param name="remoteFileName">要下载的服务器文件名</param>
/// <param name="localPath">下载到本地的路径</param>
public void DownloadFile(string remoteFileName, string localPath)
{
this.DownloadFile(remoteFileName, localPath, false);
}
/// <summary>
/// 下载服务器文件到本地
/// </summary>
/// <param name="remoteFileName">要下载的服务器文件名</param>
/// <param name="localPath">下载到本地的路径</param>
/// <param name="overWriteFile">是否要重写本地的文件</param>
public void DownloadFile(string remoteFileName, string localPath, bool overWriteFile)
{
this.DownloadFile(remoteFileName, localPath, remoteFileName, overWriteFile);
}
/// <summary>
/// 下载服务器文件到本地
/// </summary>
/// <param name="remoteFileName">要下载的服务器文件名</param>
/// <param name="localPath">下载到本地的路径</param>
/// <param name="localFileName">下载到本地的文件重命名为</param>
public void DownloadFile(string remoteFileName, string localPath, string localFileName)
{
this.DownloadFile(remoteFileName, localPath, localFileName, false);
}
/// <summary>
/// 下载服务器文件到本地
/// </summary>
/// <param name="remoteFileName">要下载的服务器文件名</param>
/// <param name="localPath">下载到本地的路径</param>
/// <param name="localFileName">下载到本地的文件重命名为</param>
/// <param name="overWriteFile">是否要重写本地的文件</param>
public void DownloadFile(string remoteFileName, string localPath, string localFileName, bool overWriteFile)
{
byte\[\] fileBytes = this.DownloadFile(remoteFileName);
if (fileBytes != null)
{
using (FileStream fileStream = new FileStream(Path.Combine(localPath, overWriteFile ?
localFileName : Gadget.ReturnFileNameWithCurrentDate(localFileName)), FileMode.Create))
{
fileStream.Write(fileBytes, , fileBytes.Length);
fileStream.Flush();
}
}
}
/// <summary>
/// 下载服务器文件到本地
/// </summary>
/// <param name="RemoteFileName">要下载的服务器文件名</param>
/// <returns>文件的字节流</returns>
public byte\[\] DownloadFile(string RemoteFileName)
{
this.OpenResponse(RemoteFileName, WebRequestMethods.Ftp.DownloadFile);
using (Stream stream = this.response.GetResponseStream())
{
using (MemoryStream memoryStream = new MemoryStream(Constant.FTP.CapacityofMemeoryStream))
{
byte\[\] buffer = new byte\[Constant.FTP.LenOfBuffer\];
int bytesRead = ;
int TotalRead = ;
while (true)
{
bytesRead = stream.Read(buffer, , buffer.Length);
TotalRead += bytesRead;
if (bytesRead == )
break;
memoryStream.Write(buffer, , bytesRead);
}
return memoryStream.Length > ? memoryStream.ToArray() : null;
}
}
}
/// <summary>
/// 删除服务器文件
/// </summary>
/// <param name="directoryPath">要删除的文件路径</param>
/// <param name="fileName">要删除的文件名</param>
public void DeleteFile(string directoryPath, string fileName)
{
this.DeleteFile(directoryPath + fileName);
}
/// <summary>
/// 删除服务器文件
/// </summary>
/// <param name="fileName">要删除的文件名</param>
public void DeleteFile(string fileName)
{
this.OpenResponse(fileName, WebRequestMethods.Ftp.DeleteFile);
}
/// <summary>
/// 列出服务器上指定目录下的所有文件
/// </summary>
/// <param name="directoryPath">指定的目录</param>
/// <returns>文件名列表</returns>
public string\[\] LisFiles(string directoryPath)
{
try
{
List<string> filesList = new List<string>();
this.OpenResponse(directoryPath, WebRequestMethods.Ftp.ListDirectory);
using (StreamReader streamReader = new StreamReader(this.response.GetResponseStream(), System.Text.Encoding.Default))
{
return Gadget.SplitString(streamReader.ReadToEnd(), Constant.TextConstant.FtpNewLine);
}
}
catch
{
return null;
}
}
/// <summary>
/// 列出服务器上指定目录下的所有子目录
/// </summary>
/// <param name="directoryPath">指定的目录</param>
/// <returns>子目录名列表</returns>
public string\[\] ListDirectories(string directoryPath)
{
List<string> directoriesList = new List<string>();
this.OpenResponse(directoryPath, WebRequestMethods.Ftp.ListDirectoryDetails);
using (StreamReader streamReader = new StreamReader(this.response.GetResponseStream()))
{
string line = streamReader.ReadLine();
if (line != null)
{
while (line != null)
{
line = line.Substring(line.LastIndexOf(Constant.TextConstant.Colon) + Constant.FTP.LenToDirectory);
if (!line.StartsWith(Constant.FileConstant.FileTypeSeperator))
{
directoriesList.Add(line);
}
line = streamReader.ReadLine();
}
return directoriesList.ToArray<string>();
}
}
return null;
}
/// <summary>
/// 检查指定的目录是否在服务器上存在
/// </summary>
/// <param name="directory">指定的目录</param>
/// <returns>如果存在返回true,否则返回false</returns>
public bool DirectoryExist(string directory)
{
try
{
this.OpenResponse(directory, WebRequestMethods.Ftp.GetDateTimestamp);
return true;
}
catch (Exception)
{
return false;
}
}
/// <summary>
/// 检查指定的文件是否在服务器上存在
/// </summary>
/// <param name="directoryPath">指定的目录</param>
/// <param name="remoteFileName">指定的文件</param>
/// <returns>如果存在返回true,否则返回false</returns>
public bool FileExist(string directoryPath, string remoteFileName)
{
string\[\] fileNames = this.LisFiles(directoryPath);
foreach (string fileName in fileNames)
{
if (string.Compare(fileName, remoteFileName, true) == )
{
return true;
}
}
return false;
}
/// <summary>
/// 释放资源
/// </summary>
public void Dispose()
{
this.Close();
}
/// <summary>
/// 释放资源
/// </summary>
public void Close()
{
if (this.response != null)
{
this.response.Close();
this.response = null;
}
}
}
、
public class Constant
{
public class TextConstant
{
public static readonly string Tab = "\t";
public static readonly string NewLine = "\n";
public static readonly string UnderLine = "_";
public static readonly string FtpNewLine = "\r\n";
public static readonly string Colon = ":";
}
public class HtmlConstant
{
public static readonly string NewLine = "<br />";
}
public class FileConstant
{
public static readonly string FileTypeForTXT = ".txt";
public static readonly string FileTypeForExcel = ".xls";
public static readonly string FileTypeForZip = ".zip";
public static readonly string FileTypeSeperator = ".";
public static readonly string FileFullMatchSymbol = "\*.\*";
public static readonly string FolderSeperator = @"\\";
}
public class DatetimeFormat
{
public static readonly string YYMMDDHHMMSS = "yyMMddHHmmss";
}
public class FTP
{
public static readonly int LenToDirectory = ;
public static readonly int LenOfBuffer = ;
public static readonly int CapacityofMemeoryStream = \* ;
}
、
public class Gadget
{
public static bool CheckDataSetIsNullOrNot(DataSet dst)
{
return dst != null && dst.Tables.Count > && dst.Tables[].Rows.Count > ;
}
public static string ReturnFileNameWithCurrentDate(string fileName)
{
return Path.GetFileNameWithoutExtension(fileName) + Constant.TextConstant.UnderLine + DateTime.Now.ToString(Constant.DatetimeFormat.YYMMDDHHMMSS) + Constant.FileConstant.FileTypeSeperator + Path.GetExtension(fileName);
}
public static string\[\] SplitString(string str, string split)
{
return str.Split(new string\[\] { split }, StringSplitOptions.RemoveEmptyEntries);
}
}
FTP查看,下载,移动,删除,测试代码:
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Net;
using System.Text;
namespace DealerDailyJob
{
public class Helper
{
private string requestUriString = string.Empty;
private string userName = string.Empty;
private string password = string.Empty;
private FtpWebRequest request;
private FtpWebResponse response;
///
/// 登陆IP
/// 用户名
/// 密码
public Helper(string RequestUriString, string UserName, string Password)
{
this.requestUriString = "ftp://" + RequestUriString + "/";
this.userName = UserName;
this.password = Password;
}
///
/// FTP路径
/// FTP方法
private void OpenRequest(string uriString, string method)
{
try
{
this.request = WebRequest.Create(new Uri(this.requestUriString + uriString)) as FtpWebRequest;
this.request.Credentials = new NetworkCredential(userName, password);
this.request.UseBinary = true;
this.request.Method = method;
}
catch
{
}
}
/// <summary>
/// 返回FtpWebResponse
/// </summary>
/// <param name="uriString">FTP路径</param>
/// <param name="method">FTP方法</param>
private void OpenResponse(string uriString, string method)
{
try
{
this.OpenRequest(uriString, method);
this.response = this.request.GetResponse() as FtpWebResponse;
}
catch
{
}
}
/// <summary>
/// 删除ftp上的文件
/// </summary>
/// <param name="file">服务器上的文件路径</param>
public void Delete(string file)
{
this.OpenResponse(file, WebRequestMethods.Ftp.DeleteFile);
}
/// <summary>
/// 移动ptf上的文件
/// </summary>
/// <param name="uName">登录名</param>
/// <param name="uPwd">密码</param>
/// <param name="Name">文件</param>
/// <param name="ftpServerIP">登陆地址</param>
public void Cut(string uName, string uPwd, string Name,string ftpServerIP)
{
request = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + ftpServerIP + "/in/" + Name)); //x代表实际Ip,这里用未知数代替
request.Method = WebRequestMethods.Ftp.Rename;
request.KeepAlive = false;
request.RenameTo = "~/bk/" + Name; //这里用的是绝对路径,大家可以根据实际情况修改
request.UseBinary = true;
request.Credentials = new NetworkCredential(uName, uPwd);
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
Stream ftpStream = response.GetResponseStream();
ftpStream.Close();
response.Close();
}
/// <summary>
/// 列出服务器上指定目录下的所有文件
/// </summary>
/// <param name="directoryPath">指定的目录</param>
/// <returns>文件名列表</returns>
public string\[\] LisFiles(string directoryPath)
{
try
{
List<string> filesList = new List<string>();
this.OpenResponse(directoryPath, WebRequestMethods.Ftp.ListDirectory);
using (StreamReader streamReader = new StreamReader(this.response.GetResponseStream(), System.Text.Encoding.Default))
{
return Gadget.SplitString(streamReader.ReadToEnd(), Constant.TextConstant.FtpNewLine);
}
}
catch
{
return null;
}
}
/// <summary>
/// 下载服务器文件到本地
/// </summary>
/// <param name="remoteFileName">要下载的服务器文件名</param>
/// <param name="localPath">下载到本地的路径</param>
public void DownloadFile(string remoteFileName, string localPath)
{
this.DownloadFile(remoteFileName, localPath, false);
}
/// <summary>
/// 下载服务器文件到本地
/// </summary>
/// <param name="remoteFileName">要下载的服务器文件名</param>
/// <param name="localPath">下载到本地的路径</param>
/// <param name="overWriteFile">是否要重写本地的文件</param>
public void DownloadFile(string remoteFileName, string localPath, bool overWriteFile)
{
this.DownloadFile(remoteFileName, localPath, remoteFileName, overWriteFile);
}
/// <summary>
/// 下载服务器文件到本地
/// </summary>
/// <param name="remoteFileName">要下载的服务器文件名</param>
/// <param name="localPath">下载到本地的路径</param>
/// <param name="localFileName">下载到本地的文件重命名为</param>
public void DownloadFile(string remoteFileName, string localPath, string localFileName)
{
this.DownloadFile(remoteFileName, localPath, localFileName, false);
}
/// <summary>
/// 下载服务器文件到本地
/// </summary>
/// <param name="remoteFileName">要下载的服务器文件名</param>
/// <param name="localPath">下载到本地的路径</param>
/// <param name="localFileName">下载到本地的文件重命名为</param>
/// <param name="overWriteFile">是否要重写本地的文件</param>
public void DownloadFile(string remoteFileName, string localPath, string localFileName, bool overWriteFile)
{
byte\[\] fileBytes = this.DownloadFile(remoteFileName);
if (fileBytes != null)
{
using (FileStream fileStream = new FileStream(Path.Combine(localPath, overWriteFile ?
localFileName : Gadget.ReturnFileNameWithCurrentDate(localFileName)), FileMode.Create))
{
fileStream.Write(fileBytes, , fileBytes.Length);
fileStream.Flush();
}
}
}
/// <summary>
/// 下载服务器文件到本地
/// </summary>
/// <param name="RemoteFileName">要下载的服务器文件名</param>
/// <returns>文件的字节流</returns>
public byte\[\] DownloadFile(string RemoteFileName)
{
this.OpenResponse(RemoteFileName, WebRequestMethods.Ftp.DownloadFile);
using (Stream stream = this.response.GetResponseStream())
{
using (MemoryStream memoryStream = new MemoryStream(Constant.FTP.CapacityofMemeoryStream))
{
byte\[\] buffer = new byte\[Constant.FTP.LenOfBuffer\];
int bytesRead = ;
int TotalRead = ;
while (true)
{
bytesRead = stream.Read(buffer, , buffer.Length);
TotalRead += bytesRead;
if (bytesRead == )
break;
memoryStream.Write(buffer, , bytesRead);
}
return memoryStream.Length > ? memoryStream.ToArray() : null;
}
}
}
}
public class Gadget
{
public static bool CheckDataSetIsNullOrNot(DataSet dst)
{
return dst != null && dst.Tables.Count > && dst.Tables\[\].Rows.Count > ;
}
public static string ReturnFileNameWithCurrentDate(string fileName)
{
string name = Path.GetFileNameWithoutExtension(fileName) + Constant.TextConstant.UnderLine + DateTime.Now.ToString(Constant.DatetimeFormat.YYMMDDHHMMSS) + Constant.FileConstant.FileTypeSeperator + Path.GetExtension(fileName);
return Path.GetFileNameWithoutExtension(fileName) + Path.GetExtension(fileName);
}
public static string\[\] SplitString(string str, string split)
{
return str.Split(new string\[\] { split }, StringSplitOptions.RemoveEmptyEntries);
}
}
public class Constant
{
public class TextConstant
{
public static readonly string Tab = "\\t";
public static readonly string NewLine = "\\n";
public static readonly string UnderLine = "\_";
public static readonly string FtpNewLine = "\\r\\n";
public static readonly string Colon = ":";
}
public class HtmlConstant
{
public static readonly string NewLine = "<br />";
}
public class FileConstant
{
public static readonly string FileTypeForTXT = ".txt";
public static readonly string FileTypeForExcel = ".xls";
public static readonly string FileTypeForZip = ".zip";
public static readonly string FileTypeSeperator = ".";
public static readonly string FileFullMatchSymbol = "\*.\*";
public static readonly string FolderSeperator = @"\\";
}
public class DatetimeFormat
{
public static readonly string YYMMDDHHMMSS = "yyMMddHHmmss";
}
public class FTP
{
public static readonly int LenToDirectory = ;
public static readonly int LenOfBuffer = ;
public static readonly int CapacityofMemeoryStream = \* ;
}
}
}
手机扫一扫
移动阅读更方便
你可能感兴趣的文章