FTP 文件上传跟下载

https://jingyan.baidu.com/article/f54ae2fc3521d51e92b849c7.html

注意电脑用户名称不能是FTP之前设置为FTP用户名称一直导致登录错误 如上网址可以进行FTP的电脑设置

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using System.Threading;

namespace TCPFileDownUp
{
    class Program
    {
        static void Main(string[] args)
        {

            //暂时只做了文件上传 没有做文件夹上传即文件夹内容中所包含的所有东西上传操作
            List<string> dirs = GetDirctory("LocalUserDemo");


            DownloadFile(@"F:\下载的文件", "LocalUserDemo", "DUCT.zip", @"192.168.1.43:58888/", "fuck", "1234");

            Console.ReadKey();


            FileInfo fileInfo = new FileInfo(@"F:\黄成\PE1110.zip");
            UploadFile(fileInfo, "LocalUserDemo", @"192.168.1.43:58888/", "fuck", "1234");


            Console.ReadKey();


        }









        /// <summary>
        /// 上传文件
        /// </summary>
        /// <param name="fileinfo">需要上传的文件</param>
        /// <param name="targetDir">目标路径</param>
        /// <param name="hostname">ftp地址</param>
        /// <param name="username">ftp用户名</param>
        /// <param name="password">ftp密码</param>
        public static void UploadFile(FileInfo fileinfo, string targetDir, string hostname, string username, string password)
        {
            //1. check target
            string target;
            if (targetDir.Trim() == "")
            {
                return;
            }
            target = Guid.NewGuid().ToString();  //使用临时文件名


            string URI = "FTP://" + hostname + "/" + targetDir + "/" + target;
            ///WebClient webcl = new WebClient();
            System.Net.FtpWebRequest ftp = GetRequest(URI, username, password);

            //设置FTP命令 设置所要执行的FTP命令,
            //ftp.Method = System.Net.WebRequestMethods.Ftp.ListDirectoryDetails;//假设此处为显示指定路径下的文件列表
            ftp.Method = System.Net.WebRequestMethods.Ftp.UploadFile;
            //指定文件传输的数据类型
            ftp.UseBinary = true;
            ftp.UsePassive = true;

            //告诉ftp文件大小
            ftp.ContentLength = fileinfo.Length;
            //缓冲大小设置为2KB
            const int BufferSize = 2048;
            byte[] content = new byte[BufferSize - 1 + 1];
            int dataRead;
            int sumTotal = 0;
            //打开一个文件流 (System.IO.FileStream) 去读上传的文件
            using (FileStream fs = fileinfo.OpenRead())
            {
                try
                {
                    //把上传的文件写入流
                    using (Stream rs = ftp.GetRequestStream())
                    {
                        do
                        {
                            //每次读文件流的2KB
                            dataRead = fs.Read(content, 0, BufferSize);

                            //进度

                            sumTotal += dataRead;
                            double RateOfProgress = sumTotal * 1.0 / fileinfo.Length;
                            Console.WriteLine(RateOfProgress);

                            rs.Write(content, 0, dataRead);
                        } while (!(dataRead < BufferSize));
                        rs.Close();
                    }

                }
                catch (Exception ex) { }
                finally
                {
                    fs.Close();
                }

            }

            ftp = null;
            //设置FTP命令
            ftp = GetRequest(URI, username, password);
            ftp.Method = System.Net.WebRequestMethods.Ftp.Rename; //改名
            ftp.RenameTo = fileinfo.Name;
            try
            {
                ftp.GetResponse();
            }
            catch (Exception ex)
            {
                //出问题就删除
                ftp = GetRequest(URI, username, password);
                ftp.Method = System.Net.WebRequestMethods.Ftp.DeleteFile; //删除
                ftp.GetResponse();
                throw ex;
            }
            finally
            {
                //fileinfo.Delete();
            }

            // 可以记录一个日志  "上传" + fileinfo.FullName + "上传到" + "FTP://" + hostname + "/" + targetDir + "/" + fileinfo.Name + "成功." );
            ftp = null;

            #region
            /*****
             *FtpWebResponse
             * ****/
            //FtpWebResponse ftpWebResponse = (FtpWebResponse)ftp.GetResponse();
            #endregion
        }



        /// <summary>
        /// 从ftp服务器上获得文件夹列表
        /// </summary>
        /// <param name="RequedstPath">服务器下的相对路径</param>
        /// <returns></returns>
        public static List<string> GetDirctory(string RequedstPath)
        {
            List<string> strs = new List<string>();
            try
            {
                string uri = @"ftp://192.168.1.43:58888/" + RequedstPath;   //目标路径 path为服务器地址
                FtpWebRequest reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
                // ftp用户名和密码
                reqFTP.Credentials = new NetworkCredential("fuck", "1234");
                reqFTP.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
                WebResponse response = reqFTP.GetResponse();
                StreamReader reader = new StreamReader(response.GetResponseStream());//中文文件名

                string line = reader.ReadLine();
                while (line != null)
                {
                    if (line.Contains("<DIR>"))
                    {
                        string msg = line.Substring(line.LastIndexOf("<DIR>") + 5).Trim();
                        strs.Add(msg);
                    }
                    line = reader.ReadLine();
                }
                reader.Close();
                response.Close();
                return strs;
            }
            catch (Exception ex)
            {
                Console.WriteLine("获取目录出错:" + ex.Message);
            }
            return strs;
        }
        private static FtpWebRequest GetRequest(string URI, string username, string password)
        {
            //根据服务器信息FtpWebRequest创建类的对象
            FtpWebRequest result = (FtpWebRequest)FtpWebRequest.Create(URI);
            //提供身份验证信息
            result.Credentials = new System.Net.NetworkCredential(username, password);
            //设置请求完成之后是否保持到FTP服务器的控制连接,默认值为true
            result.KeepAlive = false;
            return result;
        }


        /// <summary>
        /// 获取文件大小
        /// </summary>
        /// <param name="file">ip服务器下的相对路径</param>
        /// <returns>文件大小</returns>
        public static int GetFileSize(string file, string username, string password)
        {
            StringBuilder result = new StringBuilder();
            FtpWebRequest request;
            try
            {
                request = (FtpWebRequest)FtpWebRequest.Create(new Uri(file));
                request.UseBinary = true;
                request.UsePassive = false;
                request.KeepAlive = false;
                request.Credentials = new NetworkCredential(username, password);//设置用户名和密码
                request.Method = WebRequestMethods.Ftp.GetFileSize;

                int dataLength = (int)request.GetResponse().ContentLength;

                return dataLength;
            }
            catch (Exception ex)
            {
                Console.WriteLine("获取文件大小出错:" + ex.Message);
                return -1;
            }
        }




        /// <summary>
        /// 下载文件
        /// </summary>
        /// <param name="localDir">下载至本地路径</param>
        /// <param name="FtpDir">ftp目标文件路径</param>
        /// <param name="FtpFile">从ftp要下载的文件名</param>
        /// <param name="hostname">ftp地址即IP</param>
        /// <param name="username">ftp用户名</param>
        /// <param name="password">ftp密码</param>
        public static void DownloadFile(string localDir, string FtpDir, string FtpFile, string hostname, string username, string password)
        {




            string URI = "FTP://" + hostname + "/" + FtpDir + "/" + FtpFile;
            int FileTotal = GetFileSize(URI, username, password);

            string tmpname = Guid.NewGuid().ToString();
            //本地路径
            string localfile = localDir + @"\" + tmpname;

            System.Net.FtpWebRequest ftp = GetRequest(URI, username, password);
            ftp.Method = System.Net.WebRequestMethods.Ftp.DownloadFile;
            //很重要 如果要多次访问这个地方要为false keepAlive则设成false,一个查询请求完了后就关闭 因为上面做了一个查询 查询文件大小
            ftp.KeepAlive = false;
            ftp.UseBinary = true;
            ftp.UsePassive = false;
            int bufferCount = 40960;
            //long f = ftp.ContentLength;
            FtpWebResponse response = (FtpWebResponse)ftp.GetResponse();
            using (Stream responseStream = response.GetResponseStream())
            {
                using (FileStream fs = new FileStream(localfile, FileMode.CreateNew))
                {
                    try
                    {
                        byte[] buffer = new byte[bufferCount];
                        int read = 0;
                        int TotalByte = 0;
                        do
                        {
                            //把流写到buffer的byte数组中
                            read = responseStream.Read(buffer, 0, buffer.Length);
                            //下载的进度
                            TotalByte += read;
                            //下载的进度
                            double k = TotalByte * 1.0 / FileTotal;
                            Console.WriteLine(k);
                            //
                            fs.Write(buffer, 0, read);
                        } while (!(read == 0));
                    }
                    catch (Exception ex)
                    {
                        //catch error and delete file only partially downloaded
                        fs.Close();
                        //delete target file as it's incomplete
                        File.Delete(localfile);
                        throw ex;
                        Console.WriteLine(ex.Message);
                    }
                    Console.WriteLine("over");

                }


            }



            //using ()
            //{
            //    using ()
            //    {
            //        //loop to read & write to file
            //        using ()
            //        {

            //        }
            //    }
            //}



            //try
            //{
            //    //File.Delete(localDir + @"\" + FtpFile);
            //    //File.Move(localfile, localDir + @"\" + FtpFile);


            //    //ftp = null;
            //    //ftp = GetRequest(URI, username, password);
            //    //ftp.Method = System.Net.WebRequestMethods.Ftp.DeleteFile;
            //    //ftp.GetResponse();

            //}
            //catch (Exception ex)
            //{
            //    File.Delete(localfile);
            //    throw ex;
            //}

            // 记录日志 "从" + URI.ToString() + "下载到" + localDir + @"\" + FtpFile + "成功." );
            //ftp = null;
        }

    }
}

 

转载于:https://www.cnblogs.com/yangshasha/p/7879867.html

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值