FTB操作
一些参考案例下面是一些常用的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;
/// <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)
{
ftpServerIP = FtpServerIP;
ftpRemotePath = FtpRemotePath;
ftpUserID = FtpUserID;
ftpPassword = FtpPassword;
ftpURI = "ftp://" + ftpServerIP + "/" + ftpRemotePath + "/";
}
/// <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));
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);
}
}
/// <summary>
/// 下载
/// </summary>
/// <param name="filePath"></param>
/// <param name="fileName"></param>
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);
}
}
/// <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.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);
}
}
/// <summary>
/// 获取当前目录下明细(包含文件和文件夹)
/// </summary>
/// <returns></returns>
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;
}
}
/// <summary>
/// 获取FTP文件列表包括文件夹
/// </summary>
/// <returns></returns>
private string[] GetAllList(string url,string userid,string password)
{
List<string> list = new List<string>();
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();
}
/// <summary>
/// 获取当前目录下文件列表 不包括文件夹
/// </summary>
/// <returns></returns>
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;
/// <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>
/// 删除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 = * ;
} }
}
FTB操作的更多相关文章
- jQuery对表格的操作及其他应用
表格操作 1.隔行变色:对普通表格进行隔行换色:单击显示高亮样式:复选框选中高亮 <!DOCTYPE html> <html> <head> <meta ht ...
- django模型操作
Django-Model操作数据库(增删改查.连表结构) 一.数据库操作 1.创建model表
- SharePoint 使用ECMAscript对象模型来操作Goup与User
这里总结了关于使用ECMAscript对象模型来操作Goup与User的常用情况,内容如下: 1.取得当前Sharepoint网站所有的Groups 2.获取当前登录用户的Title与 ...
- Visual Studio 控制台应用程序 同时使用OpenCV和matlab mat文件操作
matalb具有灵活的图像处理,代码编写起来简洁而高效.而OpenCV具有很多成熟的计算机视觉算法,能够处理很多实时的识别处理等问题,而且代码运行起来效率很高.所以如何结合两者之间的优点,是让很多学术 ...
- 关于DOM的操作以及性能优化问题-重绘重排
写在前面: 大家都知道DOM的操作很昂贵. 然后贵在什么地方呢? 一.访问DOM元素 二.修改DOM引起的重绘重排 一.访问DOM 像书上的比喻:把DOM和JavaScript(这里指ECMScri ...
- Sql Server系列:分区表操作
1. 分区表简介 分区表在逻辑上是一个表,而物理上是多个表.从用户角度来看,分区表和普通表是一样的.使用分区表的主要目的是为改善大型表以及具有多个访问模式的表的可伸缩性和可管理性. 分区表是把数据按设 ...
- C# ini文件操作【源码下载】
介绍C#如何对ini文件进行读写操作,C#可以通过调用[kernel32.dll]文件中的 WritePrivateProfileString()和GetPrivateProfileString()函 ...
- js学习笔记:操作iframe
iframe可以说是比较老得话题了,而且网上也基本上在说少用iframe,其原因大致为:堵塞页面加载.安全问题.兼容性问题.搜索引擎抓取不到等等,不过相对于这些缺点,iframe的优点更牛,跨域请求. ...
- jquery和Js的区别和基础操作
jqery的语法和js的语法一样,算是把js升级了一下,这两种语法可以一起使用,只不过是用jqery更加方便 一个页面想要使用jqery的话,先要引入一下jqery包,jqery包从网上下一个就可以, ...
随机推荐
- profix使用过程中遇到的一些问题
1.(自动 DNS 模式检测) 本地 DNS 服务可用.通过代理服务器的名称解析已禁用. 我当时遇到的问题情况是:本来是可以正常上网的,然后用软件管家进行操作后,具体我也不记得了,反正是改动了 run ...
- npm 常用指令 使用指令删除 node_modules 包
查看 npm 命令 npm help 全局命令参数 -g npm install -g 安装全局 npm uninstall -g 卸载全局 全局node包中 i5ting_toc 这个包可以把md文 ...
- Linux入门-第八周
1.用shell脚本实现自动登录机器 #!/usr/bin/expectset ip 192.168.2.192set user rootset password rootspawn ssh $use ...
- Python中的bytes
bytes_lst = [ ('创建bytes',), ('bytes可哈希',), ('编码与解码',), ('常见编码类型',), ('ord() 与 chr()',), ] 创建bytes &g ...
- mongodb安装,库操作,集合操作(表),文档操作(记录)
安装 1.下载地址 https://fastdl.mongodb.org/win32/mongodb-win32-x86_64-2008plus-ssl-4.0.8-signed.msi 2.如果报没 ...
- 最小生成树:HDU1863-畅通工程
畅通工程 Time Limit: 1000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others) Total Submissi ...
- Linux命令之---rm
命令简介 rm命令为删除一个目录中的一个或多个文件或目录,它也可以将某个目录及其下的所有文件及子目录均删除.对于链接文件,只是删除了链接,原有文件均保持不变. rm是一个危险的命令,使用的时候要特别当 ...
- Linux文件属性之文件权限介绍
1)用ls -li 查看文件列表字段 红色代表的是inode 黄色代表的是文件权限 黄色里面的第一个 - 表示文件的类型(普通类型文件) d 表示目录(directory) l 表示链接文件(link ...
- 按时按登录IP记录Linux所有用户操作日志的方法(附脚本)
PS:Linux用户操作记录一般通过命令history来查看历史记录,但是如果因为某人误操作了删除了重要的数据,这种情况下history命令就不会有什么作用了.以下方法可以实现通过记录登陆IP地址和所 ...
- Detecting iOS
Detecting iOS I am not a fan of User Agent sniffing, but here is how you would do it: var iOS = /iPa ...