FTP 文件上传整理

FTP 文件上传   忘记原文链接了,是国外的一个人写的。

上图,上代码!



代码案例下载

上传方法:
        /// <summary>
        /// Method to upload the specified file to the specified FTP Server
        /// </summary>
        /// <param name="filename">file full name to be uploaded</param>
        private void Upload(string filename)
        {
            FileInfo fileInf = new FileInfo(filename);
            string uri = "ftp://" + ftpServerIP + "/" + fileInf.Name;
            FtpWebRequest reqFTP;

            // Create FtpWebRequest object from the Uri provided
            reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + ftpServerIP + "/" + fileInf.Name));

            // Provide the WebPermission Credintials
            reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);

            // By default KeepAlive is true, where the control connection is not closed
            // after a command is executed.
            reqFTP.KeepAlive = false;

            // Specify the command to be executed.
            reqFTP.Method = WebRequestMethods.Ftp.UploadFile;

            // Specify the data transfer type.
            reqFTP.UseBinary = true;

            // Notify the server about the size of the uploaded file
            reqFTP.ContentLength = fileInf.Length;

            // The buffer size is set to 2kb
            int buffLength = 2048;
            byte[] buff = new byte[buffLength];
            int contentLen;

            // Opens a file stream (System.IO.FileStream) to read the file to be uploaded
            FileStream fs = fileInf.OpenRead();

            try
            {
                // Stream to which the file to be upload is written
                Stream strm = reqFTP.GetRequestStream();

                // Read from the file stream 2kb at a time
                contentLen = fs.Read(buff, 0, buffLength);

                // Till Stream content ends
                while (contentLen != 0)
                {
                    // Write Content from the file stream to the FTP Upload Stream
                    strm.Write(buff, 0, contentLen);
                    contentLen = fs.Read(buff, 0, buffLength);
                }

                // Close the file stream and the Request Stream
                strm.Close();
                fs.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Upload Error");
            }
        }

        #region 判断文件夹是否存在
        /// <summary>
        /// 判断文件夹是否存在
        /// </summary>
        /// <param name="ftpFilePath"></param>
        /// <returns></returns>
        private bool CheckDireExist(string ftpParFilePath, string ftpSonFilePath)
        {
            FtpWebRequest ftpWebRequest = null; WebResponse webResponse = null;
            StreamReader reader = null;
            try
            {

                string uri = "ftp://" + ftpServerIP + "/" + ftpParFilePath;
                ftpWebRequest = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
                ftpWebRequest.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
                ftpWebRequest.Method = WebRequestMethods.Ftp.ListDirectory;
                ftpWebRequest.UsePassive = false;  //选择主动还是被动模式 ,
                ftpWebRequest.KeepAlive = false;
                webResponse = ftpWebRequest.GetResponse();
                reader = new StreamReader(webResponse.GetResponseStream(), Encoding.Default);
                string line = reader.ReadLine();
                while (line != null)
                {
                    if (line.ToLower() == ftpSonFilePath.ToLower())
                        return true;
                    line = reader.ReadLine();
                }
            }
            catch (Exception e)
            {
                throw e;
            }
            finally
            {
                if (reader != null) reader.Close();
                if (webResponse != null) webResponse.Close();

            } return false;
        }

        #endregion

        #region 创建目录
        /// <summary>
        ///  文件路径如:/a/a.1/a.2, 如果a.1 a.2 不存在,也将创建
        /// </summary>
        /// <param name="strDirePath"></param>
        public void MakeMultiFTPDire(string strDirePath)
        {
            if (string.IsNullOrEmpty(strDirePath)) return;

            #region 修改目录字符串
            //如果第一个字符不是斜杠,则添加斜杠
            if (strDirePath.IndexOf('/') != 0)
            {
                strDirePath = "/" + strDirePath;
            }

            //去除最后一个斜杠
            if (strDirePath.LastIndexOf('/') == strDirePath.Length - 1)
            {
                strDirePath = strDirePath.Substring(0, strDirePath.Length - 1);
            }
            #endregion

            #region 创建目录
            string[] strArray = strDirePath.Split('/');
            string strParPath = "";   //父节点
            string strSonPath = "/";   //子节点

            for (int i = 0; i < strArray.Length - 1; i++)
            {
                strParPath += strArray[i] + "/";
                strSonPath += strArray[i + 1] + "/";
                if (!CheckDireExist(strParPath, strArray[i + 1])) MakeDir(strSonPath);
            }
            #endregion
        }

        /// <summary>
        /// 在根目录创建目录,
        /// </summary>
        /// <param name="dirName"></param>
        private void MakeDir(string dirName)
        {
            FtpWebRequest reqFTP;
            try
            {
                // dirName = name of the directory to create.
                reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + ftpServerIP + "/" + dirName.TrimStart('/')));
                reqFTP.Method = WebRequestMethods.Ftp.MakeDirectory;
                reqFTP.UseBinary = true;
                reqFTP.UsePassive = false;  //选择主动还是被动模式 ,
                reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
                FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
                Stream ftpStream = response.GetResponseStream();

                ftpStream.Close();
                response.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show("创建目录" + dirName + "失败," + ex.Message);
            }
        }

        #endregion


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值