zoukankan      html  css  js  c++  java
  • 项目运用中的FTP上传实现

    入口程序:

    string IP = System.Configuration.ConfigurationManager.AppSettings["IP"].ToString();
    string UName = System.Configuration.ConfigurationManager.AppSettings["UserName"].ToString();
    string PWD = System.Configuration.ConfigurationManager.AppSettings["PWD"].ToString();
    FTPClient.FtpHelper ftpHelper = new FtpHelper(IP,UName,PWD);//入口
    
    int count =Convert.ToInt32( System.Configuration.ConfigurationManager.AppSettings["count"]); //ftp上传重试次数
    string ftpPath = System.Configuration.ConfigurationManager.AppSettings["ftpPath"].ToString();
    //日志记录 Assist.Log.VisitLog.WriteLog(DateTime.Now.ToString()
    + "开始上传Android包 id=" + intMagID.ToString()); bool Android= ftpHelper.TryUpload(AppDomain.CurrentDomain.BaseDirectory+ @"OutPut\" + intMagID + "\\ad15_" + intMagID + ".apk", ftpPath+"\\"+ intMagID,count);
                                //string filename, string FTPPath, int count   
    if (Android == false)   {
        Assist.Log.VisitLog.WriteLog(DateTime.Now.ToString()
    + "上传Android包失败 id=" + intMagID.ToString());   }
      else {
    Assist.Log.VisitLog.WriteLog(DateTime.Now.ToString()
    + "上传Android包成功 id=" + intMagID.ToString()); }

     

    namespace FTPClient  ==>  public class FtpHelper

    public class FtpHelper
    {
        string ftpServerIP;
        string ftpUserID;
        string ftpPassword;
        FtpWebRequest reqFTP;
        
        public FtpHelper(string ftpServerIP, string ftpUserID, string ftpPassword)
            {
                this.ftpServerIP = ftpServerIP;
    
                this.ftpUserID = ftpUserID;
    
                this.ftpPassword = ftpPassword;
            }
        
            public bool TryUpload(string filename, string FTPPath, int count)
            {
                bool RunStatus = true;
                do
                {
                    if (RunStatus == false)
                    {
                        System.Threading.Thread.Sleep(3000);
                    }
                   
                    try
                    {
                        RunStatus = Upload(filename, FTPPath);
                    }
                    catch
                    {
                        RunStatus = false;
                    }
    
                } while (RunStatus == false && count-- > 0);
                return RunStatus;
            }    
            
            public bool Upload(string filename, string FTPPath) 
            {
                if (filename == null || filename.Length == 0) return true;//没有文件需要上传 
                FTPPath = (FTPPath == null) ? FTPPath = string.Empty : '/' + FTPPath.Replace("\\", "/") + "/";
                if (FTPPath.EndsWith("/") == false) FTPPath += "/";
                if (CreateDir(FTPPath) == false) return false;
                FileInfo fileInf = new FileInfo(filename);
                if (fileInf.Exists == false)
                {
                    OnErrorEvent("文件没有找到,文件名为:" + filename);
                    return false;//文件没有找到
                }
                string uri = "ftp://" + (ftpServerIP + FTPPath + "/" + fileInf.Name).Replace("\\", "/").Replace("///", "//").Replace("//", "/");
                Connect(uri);//连接        
                // 默认为true,连接不会被关闭
                // 在一个命令之后被执行
                reqFTP.KeepAlive = false;
                // 指定执行什么命令
                reqFTP.Method = WebRequestMethods.Ftp.UploadFile;
                // 上传文件时通知服务器文件的大小
                reqFTP.ContentLength = fileInf.Length;
                // 缓冲大小设置为kb 
                int buffLength = 2048;
                byte[] buff = new byte[buffLength];
                int contentLen;
                // 打开一个文件流(System.IO.FileStream) 去读上传的文件
                FileStream fs = fileInf.OpenRead();
                try
                {
                    // 把上传的文件写入流
                    Stream strm = reqFTP.GetRequestStream();
                    // 每次读文件流的kb
                    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();
                    return true;
                }
                catch (Exception ex)
                {
                    if (OnErrorEvent != null) OnErrorEvent(ex.Message);
                    return false;
                }
            }
    
            private void Connect(String path)//连接ftp
            {
                // 根据uri创建FtpWebRequest对象
                reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(path));
    
                // 指定数据传输类型
                 reqFTP.UseBinary = true;
                //reqFTP.UsePassive = false;
    
                // ftp用户名和密码
                reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
            }        
    
            /// <summary>
            /// 检测并自动创建目录
            /// </summary>
            /// <param name="Path"></param>
            /// <returns></returns>
            public bool CreateDir(string Path)
            {
                //检测和创建目录
                if (!(Path == null || Path.Length == 0))
                {
                    string[] Directory = Path.Split(new char[] { '\\', '/' });
                    StringBuilder strbFTPPath = new StringBuilder();
                    for (int i = 1; i < Directory.Length; i++)
                    {
                        strbFTPPath.Append(Directory[i].Replace("\\", "/") + "/");
                        string[] FTPDirectory = GetFilesDetailList(strbFTPPath.ToString());
                        if (FTPDirectory == null)
                        {
                            if (MakeDir(strbFTPPath.ToString()) == false)
                            {
                                return false;
                            }
                        }
                    }
                }
                return true;
            }
            
            //获得文件明晰
            public string[] GetFilesDetailList(string path)
            {
                return GetFileList("ftp://" + ftpServerIP + "/" + path, WebRequestMethods.Ftp.ListDirectoryDetails);
            }
            
            //创建目录
            public bool MakeDir(string dirName)
            {
                try
                {
                    string uri = "ftp://" + ftpServerIP + "/" + dirName;
                    Connect(uri);//连接     
                    reqFTP.Method = WebRequestMethods.Ftp.MakeDirectory;
                    FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
                    response.Close();
                    return true;
                }
                catch (Exception ex)
                {
                    if (OnErrorEvent != null) OnErrorEvent(ex.Message);
                    return false;
                }
    
            }
            
                
        
    }

     

  • 相关阅读:
    WPF应用程序的生命周期
    问题解决(一)在ipad上通过safari浏览文档
    C#网络编程之TCP协议(一)
    认识webMethods
    sql存储过程与webMethods
    Start to study Introduction to Algorithms
    堆和栈的区别 (转贴)
    win7平台下使用MASMPlus搭建汇编环境
    makefile
    struct类型声明的疑问
  • 原文地址:https://www.cnblogs.com/wxh19860528/p/2577441.html
Copyright © 2011-2022 走看看