工具类

IT技术2年前 (2022)更新 投稿用户
0

C#FTPHelper实现FTP服务器文件读写操作,支持SSL协议(FTP服务器为:Serv-U10.0)。

usingSystem;usingSystem.Collections.Generic;usingSystem.IO;usingSystem.Linq;usingSystem.Net;usingSystem.Net.Security;usingSystem.Security.Cryptography.X509Certificates;usingSystem.Text;namespaceFTPTest
{publicclassFTPHelper
{#region变量//////FTP请求目标///FtpWebRequestrequest=null;//////FTP呼应目标///FtpWebResponseresponse=null;//////FTP服务器长地址///publicstringFtpURI{get;privateset;}//////FTP服务器IP///publicstringServerIP{get;privateset;}//////FTP端口///publicintServerPort{get;privateset;}//////FTP用户///publicstringUsername{get;privateset;}//////FTP暗码///publicstringPassword{get;privateset;}//////是否启用SSL///publicboolEnableSsl{get;privateset;}#endregion#region结构//////初始化//////IP///端口///用户名///暗码publicFTPHelper(stringftpServerIP,intftpServerPort,stringftpUsername,stringftpPassword,boolftpEnableSsl=false)

C#


{
ServerIP=ftpServerIP;
ServerPort=ftpServerPort;
Username=ftpUsername;
Password=ftpPassword;
EnableSsl=ftpEnableSsl;
FtpURI=string.Format(“ftp://{0}:{1}/”,ftpServerIP,ftpServerPort);
}~FTPHelper()
{if(response!=null)
{
response.Close();
response=null;
}if(request!=null)
{
request.Abort();
request=null;
}
}#endregion#region方法//////建立FTP链接,回来呼应目标//////FTP地址///操作指令privateFtpWebResponseOpen(Uriuri,stringftpMethod)
{try{
request=(FtpWebRequest)FtpWebRequest.Create(uri);
request.Method=ftpMethod;
request.UseBinary=true;
request.KeepAlive=false;
request.UsePassive=true;//被动模式request.EnableSsl=EnableSsl;
request.Credentials=newNetworkCredential(Username,Password);
request.Timeout=30000;//首次衔接FTPServer时,会有一个证书分配过程。//根据验证过程,长途证书无效。ServicePointsp=request.ServicePoint;
ServicePointManager.ServerCertificateValidationCallback=newRemoteCertificateValidationCallback(ValidateServerCertificate);return(FtpWebResponse)request.GetResponse();
}catch(Exceptionex)
{returnnull;
}
}//////建立FTP链接,回来请求目标//////FTP地址///操作指令privateFtpWebRequestOpenRequest(Uriuri,stringftpMethod)
{try{
request=(FtpWebRequest)WebRequest.Create(uri);
request.Method=ftpMethod;
request.UseBinary=true;
request.KeepAlive=false;
request.UsePassive=true;//被动模式request.EnableSsl=EnableSsl;
request.Credentials=newNetworkCredential(Username,Password);
request.Timeout=30000;
ServicePointsp=request.ServicePoint;
ServicePointManager.ServerCertificateValidationCallback=newRemoteCertificateValidationCallback(ValidateServerCertificate);returnrequest;
}catch(Exceptionex)
{returnnull;
}
}//////证书验证回调///privateboolValidateServerCertificate(objectsender,X509Certificatecertificate,X509Chainchain,SslPolicyErrorssslPolicyErrors)
{returntrue;
}//////下载文件//////长途文件///本地文件publicboolGet(stringremoteFileName,stringlocalFileName)
{
response=Open(newUri(FtpURI+remoteFileName),WebRequestMethods.Ftp.DownloadFile);if(response==null)returnfalse;try{using(FileStreamoutputStream=newFileStream(localFileName,FileMode.Create))
{using(StreamftpStream=response.GetResponseStream())
{longlength=response.ContentLength;intbufferSize=2048;intreadCount;byte[]buffer=newbyte[bufferSize];
readCount=ftpStream.Read(buffer,0,bufferSize);while(readCount>0)
{
outputStream.Write(buffer,0,readCount);
readCount=ftpStream.Read(buffer,0,bufferSize);
}
}
}returntrue;
}catch{returnfalse;
}
}//////文件上传//////本地文件///长途文件publicboolPut(stringlocalFileName,stringremoteFileName)
{
FileInfofi=newFileInfo(localFileName);if(fi.Exists==false)returnfalse;
request=OpenRequest(newUri(FtpURI+remoteFileName),WebRequestMethods.Ftp.UploadFile);if(request==null)returnfalse;
request.ContentLength=fi.Length;intbuffLength=2048;byte[]buff=newbyte[buffLength];intcontentLen;try{using(varfs=fi.OpenRead())
{using(varstrm=request.GetRequestStream())
{
contentLen=fs.Read(buff,0,buffLength);while(contentLen!=0)
{
strm.Write(buff,0,contentLen);
contentLen=fs.Read(buff,0,buffLength);
}
}
}returntrue;
}catch{returnfalse;
}
}//////删除文件///publicboolDeleteFile(stringfileName)
{
response=Open(newUri(FtpURI+fileName),WebRequestMethods.Ftp.DeleteFile);returnresponse==null?false:true;
}//////创立目录///publicboolCreateDirectory(stringdirName)
{
response=Open(newUri(FtpURI+dirName),WebRequestMethods.Ftp.MakeDirectory);returnresponse==null?false:true;
}//////删除目录(包含下面一切子目录和子文件)///publicboolDeleteDirectory(stringdirName)
{varlistAll=GetDirectoryAndFiles(dirName);if(listAll==null)returnfalse;foreach(varminlistAll)
{if(m.IsDirectory)
DeleteDirectory(m.Path);elseDeleteFile(m.Path);
}
response=Open(newUri(FtpURI+dirName),WebRequestMethods.Ftp.RemoveDirectory);returnresponse==null?false:true;
}//////获取目录的文件和一级子目录信息///publicListGetDirectoryAndFiles(stringdirName)
{varfileList=newList();
response=Open(newUri(FtpURI+dirName),WebRequestMethods.Ftp.ListDirectoryDetails);if(response==null)returnfileList;try{using(varstream=response.GetResponseStream())
{using(varsr=newStreamReader(stream,Encoding.Default))
{stringline=null;while((line=sr.ReadLine())!=null)
{//line的格局如下:serv-u(文件夹为第1位为d)//drw-rw-rw-1usergroup0Jun102019BStatus//-rw-rw-rw-1usergroup625Dec72018FTP文档.txtstring[]arr=line.Split(”);if(arr.Length<12)continue;//remotePath不为空时,第1行回来值为:total10715varmodel=newFileStruct()
{
IsDirectory=line.Substring(0,3)==”drw”?true:false,
Name=arr[arr.Length-1],
Path=dirName+”/”+arr[arr.Length-1]
};if(model.Name!=”.”&&model.Name!=”..”)//扫除.和..{
fileList.Add(model);
}
}
}
}returnfileList;
}catch{returnfileList;
}
}//////获取目录的文件///publicListGetFiles(stringdirName)
{varfileList=newList();
response=Open(newUri(FtpURI+dirName),WebRequestMethods.Ftp.ListDirectory);if(response==null)returnfileList;try{using(varstream=response.GetResponseStream())
{using(varsr=newStreamReader(stream,Encoding.Default))
{stringline=null;while((line=sr.ReadLine())!=null)
{varmodel=newFileStruct()
{
Name=line,
Path=dirName+”/”+line
};
fileList.Add(model);
}
}
}returnfileList;
}catch{returnfileList;
}
}//////取得长途文件巨细///publiclongGetFileSize(stringfileName)
{
response=Open(newUri(FtpURI+fileName),WebRequestMethods.Ftp.GetFileSize);returnresponse==null?-1:response.ContentLength;
}//////文件是否存在///publicboolFileExist(stringfileName)
{longlength=GetFileSize(fileName);returnlength==-1?false:true;
}//////目录是否存在///publicboolDirectoryExist(stringdirName)
{varlist=GetDirectoryAndFiles(Path.GetDirectoryName(dirName));returnlist.Count(m=>m.IsDirectory==true&&m.Name==dirName)>0?true:false;
}//////更改目录或文件名//////老称号///新称号publicboolReName(stringoldName,stringnewName)
{
request=OpenRequest(newUri(FtpURI+oldName),WebRequestMethods.Ftp.Rename);
request.RenameTo=newName;try{
response=(FtpWebResponse)request.GetResponse();returnresponse==null?false:true;
}catch{returnfalse;
}
}#endregion}//////FTP文件类///publicclassFileStruct
{//////是否为目录///publicboolIsDirectory{get;set;}//////创立时刻(FTP上无法取得时刻)/////publicDateTimeCreateTime{get;set;}//////文件或目录称号///publicstringName{get;set;}//////途径///publicstringPath{get;set;}
}
}

© 版权声明
好牛新坐标 广告
版权声明:
1、IT大王遵守相关法律法规,由于本站资源全部来源于网络程序/投稿,故资源量太大无法一一准确核实资源侵权的真实性;
2、出于传递信息之目的,故IT大王可能会误刊发损害或影响您的合法权益,请您积极与我们联系处理(所有内容不代表本站观点与立场);
3、因时间、精力有限,我们无法一一核实每一条消息的真实性,但我们会在发布之前尽最大努力来核实这些信息;
4、无论出于何种目的要求本站删除内容,您均需要提供根据国家版权局发布的示范格式
《要求删除或断开链接侵权网络内容的通知》:https://itdw.cn/ziliao/sfgs.pdf,
国家知识产权局《要求删除或断开链接侵权网络内容的通知》填写说明: http://www.ncac.gov.cn/chinacopyright/contents/12227/342400.shtml
未按照国家知识产权局格式通知一律不予处理;请按照此通知格式填写发至本站的邮箱 wl6@163.com

相关文章