zoukankan      html  css  js  c++  java
  • FTP操作类

      /// </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<objectstring> GetFileList(string strSubPath, string strUser, string strPasswd, string strSeverIP, string strRemark)
            {
                Dictionary
    <objectstring> dict = new Dictionary<objectstring>();
                
    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<objectstring> GetExistsFile(string strFile, string strUser, string strPasswd, string strSeverIP, string strRemark)
            {
                Dictionary
    <objectstring> dict = new Dictionary<objectstring>();
                
    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
    <objectstring> dict = new Dictionary<objectstring>();
                dict 
    = GetFileList(strPath, strUser, strPasswd, strSeverIP, strRemark);
                
    //dict = GetExistsFile(strPath, strUser, strPasswd, strSeverIP, strRemark);
                if (dict.Count < 1return string.Empty;
                
    else
                {
                    
    foreach (KeyValuePair<objectstring> 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

        }
  • 相关阅读:
    springcloud(十五):搭建Zuul微服务网关
    springcloud(十四)、ribbon负载均衡策略应用案例
    springcloud(十三):Ribbon客户端负载均衡实例
    springcloud(十二):Ribbon客户端负载均衡介绍
    springcloud(十):熔断监控Hystrix Dashboard
    springcloud(九):熔断器Hystrix和Feign的应用案例
    springcloud(八):熔断器Hystrix
    springcloud(七): 使用Feign调用Eureka Server客户端服务
    springcloud(六):Eureka提供数据的客户端连接Docker的mysql
    雏龙计划
  • 原文地址:https://www.cnblogs.com/tewuapple/p/2123893.html
Copyright © 2011-2022 走看看