码迷,mamicode.com
首页 > Web开发 > 详细

Ftp进行文件的上传和下载

时间:2020-04-03 16:43:43      阅读:98      评论:0      收藏:0      [点我收藏+]

标签:dex   mes   keepalive   void   tar   private   ISE   result   files   

下载:
文件操作类


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Windows.Forms;
using System.Configuration;
using System.Net;
namespace FTP文件上传
{
    class FileOperate
    {
        private static FileOperate _fileOperate = null;
        private string _filePath = string.Empty;
        public string FilePath { get { return _filePath; } private set { _filePath = value; } }
        private FileInfo fileInfo = null;
        public  string[] files = null;
        public static FileOperate GetInstance()
        {
            if (_fileOperate == null)
                _fileOperate = new FileOperate();
            return _fileOperate;
        }
        public void OpenFile()
        {
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.Filter = "文本文件|*.*|C#文件|*.cs|所有文件|*.*|文件夹|*.File folder";
            ofd.RestoreDirectory = true;
            ofd.Multiselect = true;
            ofd.FilterIndex = 1;
            if (ofd.ShowDialog() == DialogResult.OK)
            {
                files = ofd.FileNames;
            }
        }
        public void UpLoadFile(string LocalfileName)
        {
            if (string.IsNullOrEmpty(LocalfileName))
                return;
            string url = GetUrl(ConfigManager.HostName, ConfigManager.TargetDir);
            System.Net.FtpWebRequest ftp = GetRequest(url);
            //设置FTP命令 设置所要执行的FTP命令,
            //ftp.Method = System.Net.WebRequestMethods.Ftp.ListDirectoryDetails;//假设此处为显示指定路径下的文件列表
            ftp.Method = System.Net.WebRequestMethods.Ftp.UploadFile;
            fileInfo = new FileInfo(LocalfileName);
            //指定文件传输的数据类型
            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;
            //打开一个文件流 (System.IO.FileStream) 去读上传的文件
            using (FileStream fs = fileInfo.OpenRead())
            {
                try
                {
                    //把上传的文件写入流
                    using (Stream rs = ftp.GetRequestStream())
                    {
                        do
                        {
                            //每次读文件流的2KB
                            dataRead = fs.Read(content, 0, BufferSize);
                            rs.Write(content, 0, dataRead);
                        } while (!(dataRead < BufferSize));
                        rs.Close();
                    }
                }
                catch (Exception ex) { }
                finally
                {
                    fs.Close();
                }
            }
            ftp = null;
            //设置FTP命令
            ftp = GetRequest(url);
            ftp.Method = System.Net.WebRequestMethods.Ftp.Rename; //改名
            ftp.RenameTo = fileInfo.Name;
            try
            {
                ftp.GetResponse();
            }
            catch (Exception ex)
            {
                ftp = GetRequest(url);
                ftp.Method = System.Net.WebRequestMethods.Ftp.DeleteFile; //删除
                ftp.GetResponse();
                throw ex;
            }
            finally
            {
                ftp = null;
                fileInfo.Delete();
            }
            // 可以记录一个日志  "上传" + fileinfo.FullName + "上传到" + "FTP://" + hostname + "/" + targetDir + "/" + fileinfo.Name + "成功." );
        }
        /// <summary>
        /// 下载文件
        /// </summary>
        /// <param name="FtpFilePath">Ftp的文件目录</param>
        /// <param name="FtpFileName">Ftp上的文件名称</param>
        /// <param name="localFilePath">本地的文件目录</param>
        public void DownLoadFile(string FtpFilePath,string FtpFileName,string localFilePath)
        {
            if (!IsExistDir(FtpFilePath+"/"+FtpFileName))
                return;
            string url = "ftp://" + ConfigManager.HostName +  FtpFilePath+"/"+FtpFileName;
            FtpWebRequest ftp = GetRequest(url);
            ftp.Method = WebRequestMethods.Ftp.DownloadFile;
            ftp.UseBinary = true;
            ftp.UsePassive = true;
            using(FtpWebResponse response = (FtpWebResponse)ftp.GetResponse())
            {
                using(Stream rsp = response.GetResponseStream())
                {
                    localFilePath = localFilePath + @"\" + FtpFileName;
                using(FileStream fs = new FileStream(localFilePath,FileMode.OpenOrCreate))
                {
                    try
                    {
                        byte[] buffer = new byte[2048];
                        int read = 0;
                        do
                        {
                            read = rsp.Read(buffer, 0, buffer.Length);
                            fs.Write(buffer, 0, read);
                        } while (!(read == 0));
                        fs.Flush();
                        fs.Close();
                    }
                    catch
                    {
                        //失败删除文件
                        fs.Close();
                        fileInfo = new FileInfo(localFilePath);
                        fileInfo.Delete();
                    }

                }
            }

            }

        }
        private static string GetUrl(string hostName, string targetDir)
        {
            string target = Guid.NewGuid().ToString();
            return "FTP://" + hostName + "/" + targetDir + "/" + target;
        }
        private static FtpWebRequest GetRequest(string url)
        {
            //根据服务器信息FtpWebRequest创建类的对象
            FtpWebRequest result = (FtpWebRequest)FtpWebRequest.Create(url);
            //提供身份验证信息
            result.Credentials = new System.Net.NetworkCredential(ConfigManager.UserName, ConfigManager.Password);
            //设置请求完成之后是否保持到FTP服务器的控制连接,默认值为true
            result.KeepAlive = false;
            return result;
        }
        public List<string> GetDirectorysAndFiles(string requestPath)
        {
            var dict = new List<string>();
            if (!IsExistDir(requestPath))
                return dict;
            try
            {
                string url = "ftp://" + ConfigManager.HostName +  requestPath;
                FtpWebRequest ftp = GetRequest(url);
                ftp.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
                var response = ftp.GetResponse();
                StreamReader reader = new StreamReader(response.GetResponseStream());
                string line = reader.ReadLine();
                while (line != null)
                {
                    line = line.Substring(line.LastIndexOf(‘ ‘) + 1);
                    dict.Add(line);
                    line = reader.ReadLine();
                }

                ftp = null;
                response.Close();
            }
            catch { }

            return dict;
        }
        private Boolean IsExistDir(string requestPath)
        {
            try
            {
                string url = "ftp://" + ConfigManager.HostName + "/" + requestPath;
                FtpWebRequest ftp = GetRequest(url);
                ftp.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
                var response = ftp.GetResponse();
                response.Close();
            }
            catch
            {
                return false;
            }
            return true;
        }
    }
}


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
namespace FTP文件上传
{
    class ConfigManager
    {
        //上传
        public static string HostName = ConfigurationManager.AppSettings["HostName"];
        public static string UserName = ConfigurationManager.AppSettings["UserName"];
        public static string Password = ConfigurationManager.AppSettings["Password"];
        public static string TargetDir = ConfigurationManager.AppSettings["TargetDir"];

        //下载
        //D:\ftp\New folder\Newfolder
        public static string SourceDir = @"/New folder/Newfolder";//一级目录前不加/
        //目标文件夹路径
        public static string LoadTargetDir = @"D:\buck";
    }
}

调用

  //  FileOperate.GetInstance().GetDirectorysAndFiles();
          //  FileOperate.GetInstance().OpenFile();
            //MessageBox.Show(FileOperate.GetInstance().FilePath);
          //  var file = FileOperate.GetInstance().files;
           // FileOperate.GetInstance().UpLoadFile("ss");
          //  FileOperate.GetInstance().GetDirectorysAndFiles("/New folder/Newfolder");
            FileOperate.GetInstance().DownLoadFile(@"/New folder/Newfolder", "11.zip", @"D:\buck");
           // MessageBox.Show();

  

Ftp进行文件的上传和下载

标签:dex   mes   keepalive   void   tar   private   ISE   result   files   

原文地址:https://www.cnblogs.com/hnzheng/p/12627054.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!