FtpHelper实现ftp服务器文件读写操作(C#)
最近做了一个项目,需要读取ftp服务器上的文件,于是参考了网上提供的一些帮组方法,使用过程中,出现一些小细节问题,于是本人做了一些修改,拿来分享一下
usingSystem;
usingSystem.Collections.Generic;
usingSystem.Linq;
usingSystem.Text;
usingSystem.Net;
usingSystem.IO;
usingSystem.Threading;
usingSystem.Configuration;
namespaceFtpSyn
{
publicclassFtpHelper
{
//基本设置ftp://400:ZOina2017@192.168.10.17/400backup
staticprivatestringpath=@"ftp://"+ConfigurationManager.AppSettings["FtpServerIP"].ToString()+"/";//目标路径
staticprivatestringftpip=ConfigurationManager.AppSettings["FtpServerIP"].ToString();//ftpIP地址
staticprivatestringusername=ConfigurationManager.AppSettings["FtpUserName"].ToString();//ftp用户名
staticprivatestringpassword=ConfigurationManager.AppSettings["FtpPassWord"].ToString();//ftp密码
//获取ftp上面的文件和文件夹
publicstaticstring[]GetFileList(stringdir)
{
string[]downloadFiles;
StringBuilderresult=newStringBuilder();
FtpWebRequestrequest;
try
{
request=(FtpWebRequest)FtpWebRequest.Create(newUri(path+dir));
request.UseBinary=true;
request.Credentials=newNetworkCredential(username,password);//设置用户名和密码
request.Method=WebRequestMethods.Ftp.ListDirectory;
request.UseBinary=true;
request.UsePassive=false;//选择主动还是被动模式,这句要加上的。
request.KeepAlive=false;//一定要设置此属性,否则一次性下载多个文件的时候,会出现异常。
WebResponseresponse=request.GetResponse();
StreamReaderreader=newStreamReader(response.GetResponseStream());
stringline=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();
returnresult.ToString().Split('\n');
}
catch(Exceptionex)
{
LogHelper.writeErrorLog("获取ftp上面的文件和文件夹:"+ex.Message);
downloadFiles=null;
returndownloadFiles;
}
}
///
///从ftp服务器上获取文件并将内容全部转换成string返回
///
///
///
///
publicstaticstringGetFileStr(stringfileName,stringdir)
{
FtpWebRequestreqFTP;
try
{
reqFTP=(FtpWebRequest)FtpWebRequest.Create(newUri(path+dir+"/"+fileName));
reqFTP.Method=WebRequestMethods.Ftp.DownloadFile;
reqFTP.UseBinary=true;
reqFTP.Credentials=newNetworkCredential(username,password);
reqFTP.UsePassive=false;//选择主动还是被动模式,这句要加上的。
reqFTP.KeepAlive=false;//一定要设置此属性,否则一次性下载多个文件的时候,会出现异常。
FtpWebResponseresponse=(FtpWebResponse)reqFTP.GetResponse();
StreamftpStream=response.GetResponseStream();
StreamReaderreader=newStreamReader(ftpStream);
stringfileStr=reader.ReadToEnd();
reader.Close();
ftpStream.Close();
response.Close();
returnfileStr;
}
catch(Exceptionex)
{
LogHelper.writeErrorLog("获取ftp文件并读取内容失败:"+ex.Message);
returnnull;
}
}
///
///获取文件大小
///
///ip服务器下的相对路径
///文件大小
publicstaticintGetFileSize(stringfile)
{
StringBuilderresult=newStringBuilder();
FtpWebRequestrequest;
try
{
request=(FtpWebRequest)FtpWebRequest.Create(newUri(path+file));
request.UseBinary=true;
request.Credentials=newNetworkCredential(username,password);//设置用户名和密码
request.Method=WebRequestMethods.Ftp.GetFileSize;
intdataLength=(int)request.GetResponse().ContentLength;
returndataLength;
}
catch(Exceptionex)
{
Console.WriteLine("获取文件大小出错:"+ex.Message);
return-1;
}
}
///
///文件上传
///
///原路径(绝对路径)包括文件名
///目标文件夹:服务器下的相对路径不填为根目录
publicstaticvoidFileUpLoad(stringfilePath,stringobjPath="")
{
try
{
stringurl=path;
if(objPath!="")
url+=objPath+"/";
try
{
FtpWebRequestreqFTP=null;
//待上传的文件(全路径)
try
{
FileInfofileInfo=newFileInfo(filePath);
using(FileStreamfs=fileInfo.OpenRead())
{
longlength=fs.Length;
reqFTP=(FtpWebRequest)FtpWebRequest.Create(newUri(url+fileInfo.Name));
//设置连接到FTP的帐号密码
reqFTP.Credentials=newNetworkCredential(username,password);
//设置请求完成后是否保持连接
reqFTP.KeepAlive=false;
//指定执行命令
reqFTP.Method=WebRequestMethods.Ftp.UploadFile;
//指定数据传输类型
reqFTP.UseBinary=true;
using(Streamstream=reqFTP.GetRequestStream())
{
//设置缓冲大小
intBufferLength=5120;
byte[]b=newbyte[BufferLength];
inti;
while((i=fs.Read(b,0,BufferLength))>0)
{
stream.Write(b,0,i);
}
Console.WriteLine("上传文件成功");
}
}
}
catch(Exceptionex)
{
Console.WriteLine("上传文件失败错误为"+ex.Message);
}
finally
{
}
}
catch(Exceptionex)
{
Console.WriteLine("上传文件失败错误为"+ex.Message);
}
finally
{
}
}
catch(Exceptionex)
{
Console.WriteLine("上传文件失败错误为"+ex.Message);
}
}
///
///删除文件
///
///服务器下的相对路径包括文件名
publicstaticvoidDeleteFileName(stringfileName)
{
try
{
FileInfofileInf=newFileInfo(ftpip+""+fileName);
stringuri=path+fileName;
FtpWebRequestreqFTP=(FtpWebRequest)FtpWebRequest.Create(newUri(uri));
//指定数据传输类型
reqFTP.UseBinary=true;
//ftp用户名和密码
reqFTP.Credentials=newNetworkCredential(username,password);
//默认为true,连接不会被关闭
//在一个命令之后被执行
reqFTP.KeepAlive=false;
//指定执行什么命令
reqFTP.Method=WebRequestMethods.Ftp.DeleteFile;
FtpWebResponseresponse=(FtpWebResponse)reqFTP.GetResponse();
response.Close();
}
catch(Exceptionex)
{
Console.WriteLine("删除文件出错:"+ex.Message);
}
}
///
///新建目录上一级必须先存在
///
///服务器下的相对路径
publicstaticvoidMakeDir(stringdirName)
{
try
{
stringuri=path+dirName;
FtpWebRequestreqFTP=(FtpWebRequest)FtpWebRequest.Create(newUri(uri));
//指定数据传输类型
reqFTP.UseBinary=true;
//ftp用户名和密码
reqFTP.Credentials=newNetworkCredential(username,password);
reqFTP.Method=WebRequestMethods.Ftp.MakeDirectory;
FtpWebResponseresponse=(FtpWebResponse)reqFTP.GetResponse();
response.Close();
}
catch(Exceptionex)
{
Console.WriteLine("创建目录出错:"+ex.Message);
}
}
///
///删除目录上一级必须先存在
///
///服务器下的相对路径
publicstaticvoidDelDir(stringdirName)
{
try
{
stringuri=path+dirName;
FtpWebRequestreqFTP=(FtpWebRequest)FtpWebRequest.Create(newUri(uri));
//ftp用户名和密码
reqFTP.Credentials=newNetworkCredential(username,password);
reqFTP.Method=WebRequestMethods.Ftp.RemoveDirectory;
FtpWebResponseresponse=(FtpWebResponse)reqFTP.GetResponse();
response.Close();
}
catch(Exceptionex)
{
Console.WriteLine("删除目录出错:"+ex.Message);
}
}
///
///从ftp服务器上获得文件夹列表
///
///服务器下的相对路径
///
publicstaticListGetDirctory(stringRequedstPath)
{
Liststrs=newList();
try
{
stringuri=path+RequedstPath;//目标路径path为服务器地址
FtpWebRequestreqFTP=(FtpWebRequest)FtpWebRequest.Create(newUri(uri));
//ftp用户名和密码
reqFTP.Credentials=newNetworkCredential(username,password);
reqFTP.Method=WebRequestMethods.Ftp.ListDirectoryDetails;
WebResponseresponse=reqFTP.GetResponse();
StreamReaderreader=newStreamReader(response.GetResponseStream());//中文文件名
stringline=reader.ReadLine();
while(line!=null)
{
if(line.Contains(""))
{
stringmsg=line.Substring(line.LastIndexOf("")+5).Trim();
strs.Add(msg);
}
line=reader.ReadLine();
}
reader.Close();
response.Close();
returnstrs;
}
catch(Exceptionex)
{
Console.WriteLine("获取目录出错:"+ex.Message);
}
returnstrs;
}
///
///从ftp服务器上获得文件列表
///
///服务器下的相对路径
///
publicstaticListGetFile(stringRequedstPath)
{
Liststrs=newList();
try
{
stringuri=path+RequedstPath;//目标路径path为服务器地址
FtpWebRequestreqFTP=(FtpWebRequest)FtpWebRequest.Create(newUri(uri));
//ftp用户名和密码
reqFTP.Credentials=newNetworkCredential(username,password);
reqFTP.Method=WebRequestMethods.Ftp.ListDirectoryDetails;
WebResponseresponse=reqFTP.GetResponse();
StreamReaderreader=newStreamReader(response.GetResponseStream());//中文文件名
stringline=reader.ReadLine();
while(line!=null)
{
if(!line.Contains(""))
{
stringmsg=line.Substring(39).Trim();
strs.Add(msg);
}
line=reader.ReadLine();
}
reader.Close();
response.Close();
returnstrs;
}
catch(Exceptionex)
{
Console.WriteLine("获取文件出错:"+ex.Message);
}
returnstrs;
}
}
}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。