FTPhelper用C#编写FTP程序.docx
- 文档编号:25886641
- 上传时间:2023-06-16
- 格式:DOCX
- 页数:16
- 大小:17.14KB
FTPhelper用C#编写FTP程序.docx
《FTPhelper用C#编写FTP程序.docx》由会员分享,可在线阅读,更多相关《FTPhelper用C#编写FTP程序.docx(16页珍藏版)》请在冰豆网上搜索。
FTPhelper用C#编写FTP程序
FTPhelper——用C#编写FTP程序
usingSystem;
usingSystem.Collections.Generic;
usingSystem.Text;
usingSystem.IO;
usingSystem.Net;
usingSystem.Globalization;
namespaceFtpTest1
{
publicclassFtpWeb
{
stringftpServerIP;
stringftpRemotePath;
stringftpUserID;
stringftpPassword;
stringftpURI;
///
///连接FTP
///
///
Illvparamname二"FtpRemotePath">指定FTP连接成功后的当前目录,如果不指定即默认为根目录
lllvparamname="FtpUserID">用户名vlparam>
lllvparamname="FtpPassword">密码vlparam>
publicFtpWeb(stringFtpServerIP,stringFtpRemotePath,stringFtpUserID,stringFtpPassword)
{
ftpServerIP=FtpServerIP;
ftpRemotePath=FtpRemotePath;
ftpUserID=FtpUserID;
ftpPassword=FtpPassword;ftpURI="ftp:
//"+ftpServerIP+"/";
staticvoidMain(){
//stringfile="c:
\\aq3.gifa";
//FileInfofileInf=newFileInfo(file);
//if(!
fileInf.Exists)
//{
//Console.WriteLine(file+"noexists");
//}
//else{
//Console.WriteLine("yes");
//}//Console.ReadLine();
FtpWebfw=newFtpWeb("121.11.65.10","","aa1","aa");
string[]filePaths={"c:
\\aq3.gif1","c:
\\aq2.gif1","c:
\\bsmain_runtime.log"};
Console.WriteLine(fw.UploadFile(filePaths));
Console.ReadLine();
}
//上传文件
publicstringUploadFile(string[]filePaths){
StringBuildersb=newStringBuilder();
if(filePaths!
=null&&filePaths.Length>0){
foreach(varfileinfilePaths){
sb.Append(Upload(file));
}
returnsb.ToString();
}
///
///上传文件
///
///
privatestringUpload(stringfilename)
{
FileInfofileInf=newFileInfo(filename);
if(!
fileInf.Exists){
returnfilename+"不存在!
\n";
}
stringuri=ftpURI+fileInf.Name;
FtpWebRequestreqFTP;
reqFTP=(FtpWebRequest)FtpWebRequest.Create(newUri(uri));
reqFTP.Credentials=newNetworkCredential(ftpUserID,ftpPassword);
reqFTP.KeepAlive=false;
reqFTP.Method=WebRequestMethods.Ftp.UploadFile;
reqFTP.UseBinary=true;
reqFTP.UsePassive=false;//选择主动还是被动模式
//EnteringPassiveMode
reqFTP.ContentLength=fileInf.Length;
intbuffLength=2048;
byte[]buff=newbyte[buffLength];
intcontentLen;
FileStreamfs=fileInf.OpenRead();
try
{
Streamstrm=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(Exceptionex)
return"同步"+filename+"时连接不上服务器!
\n";
//Insert_Standard_ErrorLog.Insert("FtpWeb","UploadError-->"+ex.Message);
}
return"";
}
///
///下载
///
///
///
publicvoidDownload(stringfilePath,stringfileName)
FtpWebRequestreqFTP;
try
{
FileStreamoutputStream=newFileStream(filePath+"\\"+fileName,FileMode.Create);
reqFTP=(FtpWebRequest)FtpWebRequest.Create(newUri(ftpURIfileName));
reqFTP.Method=WebRequestMethods.Ftp.DownloadFile;
reqFTP.UseBinary=true;
reqFTP.Credentials=newNetworkCredential(ftpUserID,ftpPassword);
FtpWebResponseresponse=(FtpWebResponse)reqFTP.GetResponse();
StreamftpStream=response.GetResponseStream();
longcl=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);
}
ftpStream.Close();
outputStream.Close();
response.Close();
}
catch(Exceptionex)
{
Insert_Standard_ErrorLog.Insert("FtpWeb","DownloadError-->"+ex.Message);
}
}
///
///删除文件
///
///
publicvoidDelete(stringfileName)
{
try
stringuri=ftpURI+fileName;
FtpWebRequestreqFTP;
reqFTP=
(FtpWebRequest)FtpWebRequest.Create(newUri(uri));
reqFTP.Credentials=new
NetworkCredential(ftpUserID,ftpPassword);
reqFTP.KeepAlive=false;
reqFTP.Method=
WebRequestMethods.Ftp.DeleteFile;
stringresult=String.Empty;
FtpWebResponseresponse=(FtpWebResponse)reqFTP.GetResponse();
longsize=response.ContentLength;
Streamdatastream=
response.GetResponseStream();
StreamReadersr=newStreamReader(datastream);
result=sr.ReadToEnd();
sr.Close();
datastream.Close();
response.Close();
}
catch(Exceptionex)
{
Insert_Standard_ErrorLog.Insert("FtpWeb",
"DeleteError-->"+ex.Message+"文件名:
"+fileName);
}
}
///
///获取当前目录下明细(包含文件和文件夹)
///
///
publicstring[]GetFilesDetailList()
{
string[]downloadFiles;
try
{
StringBuilderresult=newStringBuilder();
FtpWebRequestftp;
ftp=
(FtpWebRequest)FtpWebRequest.Create(newUri(ftpURI));
ftp.Credentials=new
NetworkCredential(ftpUserID,ftpPassword);
ftp.Method=
WebRequestMethods.Ftp.ListDirectoryDetails;
WebResponseresponse=ftp.GetResponse();
StreamReaderreader=new
StreamReader(response.GetResponseStream());
stringline=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"),1);
reader.Close();
response.Close();
returnresult.ToString().Split('\n');
}catch(Exceptionex)
downloadFiles=null;
Insert_Standard_ErrorLog.Insert("FtpWeb",
"GetFilesDetailListError-->"+ex.Message);
returndownloadFiles;
}
}
///
///获取当前目录下文件列表(仅文件)
///
///
publicstring[]GetFileList(stringmask)
{
string[]downloadFiles;
StringBuilderresult=newStringBuilder();
FtpWebRequestreqFTP;
try
{
reqFTP=
(FtpWebRequest)FtpWebRequest.Create(newUri(ftpURI));
reqFTP.UseBinary=true;
reqFTP.Credentials=new
NetworkCredential(ftpUserID,ftpPassword);
reqFTP.Method=
WebRequestMethods.Ftp.ListDirectory;
WebResponseresponse=reqFTP.GetResponse();
StreamReaderreader=new
StreamReader(response.GetResponseStream());
stringline=reader.ReadLine();
while(line!
=null)
{
if(mask.Trim()!
=string.Empty&&mask.Trim()!
="*.*")
{
stringmask_=mask.Substring(0,mask.IndexOf("*"));
if(line.Substring(0,mask_.Length)
==mask_)
{
result.Append(line);
result.Append("\n");
}
}
else
{
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)
{
downloadFiles=null;
if(ex.Message.Trim()!
="远程服务器返回错误
(550)文件不可用(例如,未找到文件,无法访问文件)。
")
{
Insert_Standard_ErrorLog.Insert("FtpWeb","GetFileListError-->"+ex.Message.ToString());
returndownloadFiles;
}
}
///
///获取当前目录下所有的文件夹列表(仅文件夹)
///
///
publicstring[]GetDirectoryList()
{
string[]drectory=GetFilesDetailList();
stringm=string.Empty;
foreach(stringstrindrectory)
{
if(str.Trim().Substring(0,1).ToUpper()==
"D")
m+=str.Substring(54).Trim()+"\n";
}
}
char[]n=newchar[]{'\n'};
returnm.Split(n);
}
///
///判断当前目录下指定的子目录是否存在
指定的目录名
///
///
publicboolDirectoryExist(stringRemoteDirectoryName)
string[]dirList=GetDirectoryList();
foreach(stringstrindirList)
{
if(str.Trim()==RemoteDirectoryName.Trim())
{
returntrue;
}
}
returnfalse;
}
///
远程文件名
///
publicboolFileExist(stringRemoteFileName)
{
string[]fileList=GetFileList("*.*");
foreach(stringstrinfileList)
{
if(str.Trim()==RemoteFileName.Trim())
{
returntrue;
}
}
returnfalse;
}
///
///
publicvoidMakeDir(stringdirName)
{
FtpWebRequestreqFTP;
try
{
//dirName=nameofthedirectorytocreate.
reqFTP=(FtpWebRequest)FtpWebRequest.Create(newUri(ftpURIdirName));
reqFTP.Method=
WebRequestMethods.Ftp.MakeDirectory;
reqFTP.UseBinary=true;
reqFTP.Credentials=new
NetworkCredential(ftpUserID,ftpPassword);
FtpWebResponseresponse=
(FtpWebResponse)reqFTP.GetResponse();
StreamftpStream=
response.GetResponseStream();
ftpStream.Close();
response.Close();
}
catch(Exceptionex)
{
Insert_Standard_ErrorLog.Insert("FtpWeb","MakeDirError-->"+ex.Message);
}
}
///
///
///
publiclongGetFileSize(stringfilename)
{
FtpWebRequestreqFTP;
longfileSize=0;
try
{
reqFTP=(FtpWebRequest)FtpWebRequest.Create(newUri(ftpURIfilename));
reqFTP.Method=WebRequestMethods.Ftp.GetFileSize;
reqFTP.UseBinary=true;
reqFTP.Credentials=newNetworkCredential(ftpUserID,ftpPassword);
FtpWebResponseresponse=(FtpWebResponse)reqFTP.GetResponse();
StreamftpStream=response.GetResponseStream();
fileSize=response.ContentLength;
ftpStream.Close();
response.Close();
}
catch(Exceptionex)
{
Insert_Standard_ErrorLog.Insert("FtpWeb","GetFileSizeError-->"+ex.Message);
}
returnfileSize;
}
///
///
///
publicvoidReName(stringcurrentFilename,stringnewFilename)
{
FtpWebRequestreqFTP;
try
{
reqFTP=(FtpWebRequest)FtpWebRequest.Create(newUri(ftpURIcurrentFilename));
reqFTP.Method=
WebRequestMethods.Ftp.Rename;
reqFTP.RenameTo=newFilename;
reqFTP.UseBinary=true;
reqFTP.Credentials=new
NetworkCredential(ftpUserID,ftpPassword);
FtpWebResponseresponse=
(FtpWebResponse)reqFTP.GetResponse();
StreamftpStream=response.GetResponseStream();
ftpStream.Close();
response.Close();
}
catch(Exceptionex)
{
Insert_Standard_ErrorLog.Insert("FtpWeb","ReNameError-->"+ex.Message);
}
}
//
- 配套讲稿:
如PPT文件的首页显示word图标,表示该PPT已包含配套word讲稿。双击word图标可打开word文档。
- 特殊限制:
部分文档作品中含有的国旗、国徽等图片,仅作为作品整体效果示例展示,禁止商用。设计者仅对作品中独创性部分享有著作权。
- 关 键 词:
- FTPhelper C# 编写 FTP 程序
![提示](https://static.bdocx.com/images/bang_tan.gif)