FTP操作类

ExpandedBlockStart.gif 代码
     ///   </summary>
     public   class  FTPTransmission
    {
        
#region  上传文件到FTP服务器
        
///   <summary>
        
///  上传文件到FTP服务器
        
///   </summary>
        
///   <param name="strPath"></param>
        
///   <param name="strUser"></param>
        
///   <param name="strPass"></param>
        
///   <param name="strServerIP"></param>
        
///   <returns></returns>
         public   void  UploadFileToFTP( string  localFile,  string  ftpFile,  string  strUser,  string  strPass,  string  strServerIP)
        {
            
try
            {
                FileInfo FInfo 
=   new  FileInfo(localFile);

                FtpWebRequest request 
=  (FtpWebRequest)WebRequest.Create( " ftp:// "   +  strServerIP  +   " / "   +  ftpFile);

                request.Method 
=  WebRequestMethods.Ftp.UploadFile;

                request.Credentials 
=   new  NetworkCredential(strUser, strPass);

                request.ContentLength 
=  FInfo.Length;

                
//  缓冲大小设置为2kb=======[网上评论:]缓冲的大小为2kb,无论上传大文件还是小文件,这都是一个合适的大小。
                 int  buffLength  =   2048 ;

                
byte [] buff  =   new   byte [buffLength];

                
int  contentLen;

                
//  打开一个文件流 (System.IO.FileStream) 去读上传的文件
                FileStream fs  =  FInfo.OpenRead();

                
//  把上传的文件写入流
                Stream strm  =  request.GetRequestStream();

                
//  每次读文件流的2kb
                contentLen  =  fs.Read(buff,  0 , buffLength);

                
//  流内容没有结束
                 while  (contentLen  !=   0 )
                {
                    
//  把内容从file stream 写入 upload stream
                    strm.Write(buff,  0 , contentLen);

                    contentLen 
=  fs.Read(buff,  0 , buffLength);
                }

                
//  关闭两个流
                strm.Close();
                fs.Close();

            }
            
catch  (Exception ex)
            {
                
throw  ex;
            }
        }
        
#endregion

        
#region  从FTP服务器上下载文件
        
///   <summary>
        
///  从FTP服务器上下载文件
        
///   </summary>
        
///   <param name="localFile"></param>
        
///   <param name="ftpFile"> FTP上的文件路径 </param>
        
///   <param name="ftpUserID"></param>
        
///   <param name="ftpPassword"></param>
        
///   <param name="ftpServerIP"></param>
        
///   <returns></returns>
         public   void  DownloadFileFromFTP( string  localFile,  string  ftpFile,  string  ftpUserID,  string  ftpPassword,  string  ftpServerIP)
        {
            
try
            {
                
// 如果文件夹不存在,则创建文件夹
                CreateNotExistsFolder(localFile);

                FileStream outputStream 
=   new  FileStream(localFile, FileMode.Create);

                FtpWebRequest reqFTP 
=  (FtpWebRequest)FtpWebRequest.Create( new  Uri( " ftp:// "   +  ftpServerIP  +   " / "   +  ftpFile));

                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  =   2048 ;

                
int  readCount;

                
byte [] buffer  =   new   byte [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  (Exception ex)
            {
                
throw  ex;
            }
        }
        
#endregion

        
#region  创建文件夹
        
///   <summary>
        
///  CreateNotExistsFolder
        
///   </summary>
        
///   <param name="strPathName"> 完全路径包括文件名 </param>
         public   void  CreateNotExistsFolder( string  strPathName)
        {
            FileInfo FInfo 
=   new  FileInfo(strPathName);
            
// 如果文件夹不存在,则创建文件夹
             if  ( ! Directory.Exists(FInfo.DirectoryName))
                Directory.CreateDirectory(FInfo.DirectoryName);
        }
        
#endregion

        
#region  获得FTP目录下符合要求的文件列表
        
///   <summary>
        
///  GetFileList
        
///   <param name="strFile"> FTP目标文件夹[根目录下则传入“”] </param>
        
///   <param name="strUser"> 用户名 </param>
        
///   <param name="strPasswd"> 密码 </param>
        
///   <param name="strSeverIP"> FTP服务器IP </param>
        
///   <param name="strRemark"> FTP的目标文件名(模糊查询;例如:找.lok后缀的文件,则输入参数为“.lok”) </param>
        
///   <returns> 返回找到的文件名称列表[含.lok],没有找到则返回“” </returns>
        
///   </summary>
        
///   <param name="strSubPath"></param>
        
///   <param name="strUser"></param>
        
///   <param name="strPasswd"></param>
        
///   <param name="strSeverIP"></param>
        
///   <param name="strRemark"></param>
        
///   <returns></returns>
         public  Dictionary < object string >  GetFileList( string  strSubPath,  string  strUser,  string  strPasswd,  string  strSeverIP,  string  strRemark)
        {
            Dictionary
< object string >  dict  =   new  Dictionary < object string > ();
            
string  strPath  =   string .Empty;
            
if  (strSubPath.Trim().Equals( string .Empty)) strPath  =   " ftp:// "   +  strSeverIP  +   " / " ;
            
else  strPath  =   " ftp:// "   +  strSeverIP  +   " / "   +  strSubPath  +   " / " ;
            
try
            {
                FtpWebRequest reqFTP 
=  (FtpWebRequest)FtpWebRequest.Create( new  Uri(strPath));
                reqFTP.UseBinary 
=   true ;
                reqFTP.Credentials 
=   new  NetworkCredential(strUser, strPasswd);
                reqFTP.Method 
=  WebRequestMethods.Ftp.ListDirectory;
                WebResponse response 
=  reqFTP.GetResponse();
                StreamReader reader 
=   new  StreamReader(response.GetResponseStream(), Encoding.Default,  true );
                
string  strline  =   string .Empty;

                
for  ( int  i  =   0 ; (strline  =  reader.ReadLine())  !=   null ; i ++ )
                {
                    
// strline = reader.ReadLine();
                    
// if (line == null) continue;
                    
// if (line.Contains(strRemark))
                    
// {
                    
//     reader.Close();
                    
//     response.Close();
                    
//     return line;
                    
// }
                     if  (strline.ToUpper().Contains(strRemark.ToUpper()))
                    {
                        dict.Add(strline, strline);
                    }
                }
                
                
return  dict;
            }
            
catch  (Exception ex)
            {
                
throw   new  Exception(ex.Message);
            }
            
        }
        
#endregion

        
#region  获得已有文件列表
        
public  Dictionary < object string >  GetExistsFile( string  strFile,  string  strUser,  string  strPasswd,  string  strSeverIP,  string  strRemark)
        {
            Dictionary
< object string >  dict  =   new  Dictionary < object string > ();
            
string  strPath  =   string .Empty;
            
if  (strFile.Trim().Equals( string .Empty)) strPath  =   " ftp:// "   +  strSeverIP  +   " / " ;
            
else  strPath  =   " ftp:// "   +  strSeverIP  +   " / "   +  strFile  +   " / " ;

            
try
            {
                FtpWebRequest reqFTP 
=  (FtpWebRequest)FtpWebRequest.Create( new  Uri(strPath));
                reqFTP.UseBinary 
=   true ;
                reqFTP.Credentials 
=   new  NetworkCredential(strUser, strPasswd);
                reqFTP.Method 
=  WebRequestMethods.Ftp.ListDirectory;
                WebResponse response 
=  reqFTP.GetResponse();
                StreamReader reader 
=   new  StreamReader(response.GetResponseStream(), Encoding.Default,  true );
                
string  strline  =   string .Empty;

                
for  ( int  i  =   0 ; (strline  =  reader.ReadLine())  !=   null ; i ++ )
                {
                    
if  (strline.Equals(strRemark))
                    {
                        dict.Add(strline, strline);
                        reader.Close();
                        response.Close();
                        
return  dict;
                    }
                }
                reader.Close();
                response.Close();
                
return  dict;
            }
            
catch
            {
                
return  dict;
            }
        }
        
#endregion

        
#region  根据传入参数获得FTP上符合要求的文件
        
///   <summary>
        
///  根据传入参数获得FTP上符合要求的文件
        
///   </summary>
        
///   <param name="strPath"></param>
        
///   <param name="strUser"></param>
        
///   <param name="strPasswd"></param>
        
///   <param name="strSeverIP"></param>
        
///   <param name="strRemark"></param>
        
///   <returns></returns>
         public   string  GetFile( string  strPath,  string  strUser,  string  strPasswd,  string  strSeverIP,  string  strRemark)
        {
            Dictionary
< object string >  dict  =   new  Dictionary < object string > ();
            dict 
=  GetFileList(strPath, strUser, strPasswd, strSeverIP, strRemark);
            
// dict = GetExistsFile(strPath, strUser, strPasswd, strSeverIP, strRemark);
             if  (dict.Count  <   1 return   string .Empty;
            
else
            {
                
foreach  (KeyValuePair < object string >  Kvp  in  dict)
                {
                    
if  (Kvp.Key.ToString().ToUpper().Contains(strRemark))  return  Kvp.Value;
                }
                
return   string .Empty;
            }
        }
        
#endregion

        
#region  根据传入参数删除FTP上的对应文件
        
///   <summary>
        
///  DelFile
        
///   </summary>
        
///   <param name="strFile"> 传入所需删除文件的全路径 </param>
        
///   <param name="strUser"> 用户名 </param>
        
///   <param name="strPasswd"> 密码 </param>
        
///   <param name="strSeverIP"> FTP地址 </param>
        
///   <returns></returns>
         public   bool  DelFile( string  strFile,  string  strUser,  string  strPasswd,  string  strSeverIP)
        {
            
try
            {
                FtpWebRequest reqFTP 
=  (FtpWebRequest)FtpWebRequest.Create( new  Uri( " ftp:// "   +  strSeverIP  +   " / "   +  strFile));
                reqFTP.Method 
=  WebRequestMethods.Ftp.DeleteFile;
                reqFTP.UseBinary 
=   true ;
                reqFTP.Credentials 
=   new  NetworkCredential(strUser, strPasswd);
                WebResponse response 
=  (FtpWebResponse)reqFTP.GetResponse();
                response.Close();
                
return   true ;
            }
            
catch
            {
                
return   false ;
            }
        }
        
#endregion

        
#region  在FTP上创建所需目录
        
///   <summary>
        
///  CreateDirectory
        
///   </summary>
        
///   <param name="strFile"></param>
        
///   <param name="strUser"></param>
        
///   <param name="strPasswd"></param>
        
///   <param name="strSeverIP"></param>
         public   void  CreateFTPDirectory( string  strDirectory,  string  strUser,  string  strPasswd,  string  strSeverIP)
        {
            
if  (strDirectory.Equals( string .Empty))  throw   new  Exception( " 没有传入文件夹! " );
            
string  strPath  =   " ftp:// "   +  strSeverIP  +   " / "   +  strDirectory;
            
string  strCheckPath  =  strPath.Remove(strPath.LastIndexOf( " / " +   1 );
            
string  strDircetory  =  strPath.Substring(strPath.LastIndexOf( " / " +   1 );

            
try
            {
                
#region  check exists
                FtpWebRequest reqFTP 
=  (FtpWebRequest)FtpWebRequest.Create( new  Uri(strCheckPath));
                reqFTP.UseBinary 
=   true ;
                reqFTP.Credentials 
=   new  NetworkCredential(strUser, strPasswd);
                reqFTP.Method 
=  WebRequestMethods.Ftp.ListDirectory;
                WebResponse response 
=  reqFTP.GetResponse();
                StreamReader reader 
=   new  StreamReader(response.GetResponseStream(), Encoding.Default,  true );
                
string  strline  =   string .Empty;

                
for  ( int  i  =   0 ; (strline  =  reader.ReadLine())  !=   null ; i ++ )
                {
                    
if  (strline.Equals(strDircetory))
                    {
                        reader.Close();
                        response.Close();
                        
return ;
                    }
                }
                reader.Close();
                response.Close();
                
#endregion

                
#region  Create Directory
                reqFTP 
=  (FtpWebRequest)FtpWebRequest.Create( new  Uri(strPath));
                reqFTP.UseBinary 
=   true ;
                reqFTP.Credentials 
=   new  NetworkCredential(strUser, strPasswd);
                reqFTP.Method 
=  WebRequestMethods.Ftp.MakeDirectory;
                response 
=  reqFTP.GetResponse();
                response.Close();
                
#endregion
            }
            
catch  (Exception ex)
            {
                
throw  ex;
            }
        }
        
#endregion

    }

 

转载于:https://www.cnblogs.com/9421/archive/2010/05/05/1728027.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值