Ftp进行文件的上传和下载

摘要:
使用System.Linq;使用System.Text;使用System.Configuration;命名空间FTP文件上载{classFileOperate{privatestaticFileOperate_fileOperate=null;publicstring[]files=null;

一、开篇之前,先给大家推荐一款好用的FTP工具:FTP客户端—IIs7服务器管理工具
             --官网地址:http://fwqglgj.iis7.net/cp/ftp/?cmc-zc
作为FTP客户端,它支持批量管理ftp站点。定时上传和定时下载,定时备份,且操作简洁。同时iis7服务器管理工具还是vnc客户端。并且支持批量管理管理windows及linux服务器、vps。让服务器真正实现了一站式管理,真的是非常方便。

这款软件功能丰富,主要有:

   1、自动重连
   2、自动重传
   3、定时任务 (定时上传、定时下载)
   4、自定义传输模式,线程,编码
   5、删除到回收站
   6、大量文件快速加载,边加载边传输
   7、批量连接一键关闭

接下来来欣赏下界面:

Ftp进行文件的上传和下载第1张

Ftp进行文件的上传和下载第2张

  二、下面是.net 常用的文件上传帮助类:

下载:
文件操作类
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:ftpNew folderNewfolder
        public static string SourceDir = @"/New folder/Newfolder";//一级目录前不加/
        //目标文件夹路径
        public static string LoadTargetDir = @"D:uck";
    }
}

调用

  //  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:uck");
           // MessageBox.Show();

  

免责声明:文章转载自《Ftp进行文件的上传和下载》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇基于python的种子搜索网站-开发过程能否用痰盂盛饭——谈谈在头文件中定义外部变量下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

Laravel 缓存操作

Laravel 为不同的缓存系统提供了统一的 API。缓存配置位于 config/cache.php。 Laravel 目前支持主流的缓存后端如 File、Memcached 和 Redis 等,默认是使用文件缓存。 env文件配置 ,推荐修改这里 config/cache.php 文件,不建议直接修改 默认laravel支持缓存介质:"apc", "...

System.AccessViolationException,尝试读取或写入受保护的内存。这通常指示其他内存已损坏。

从事件查看器中发现,IIS不定期崩溃并重启的现象。抓取crash dump文件后,发现能够看到异常,但没有堆栈信息(主要是只会看托管代码的堆栈,非托管的不清楚。),问题表现及dump日志的截图如下: 从dump文件的异常信息分析看,System.AccessViolationException,尝试读取或写入受保护的内存。这通常指示其他内存已损坏。...

java微信小程序参数二维码生成带背景图加字体(无限生成)

需求 :           1,因为项目需求 ,生成数以万计的二维码         2 ,每个二维码带不同的参数      3,二维码有固定背景图            4 , 往生成图片上写入 字体和编号(动态 )  设计技术 :    1,微信接口token ,nginx 缓存     2,二维码 图片定义 写字  maven  <depen...

shell中的条件判断

1.测试内容  2.测试方法  3.应用示例   在shell脚本中应用条件测试时,关键是“测试表达式”。在条件语句中测试时首先分清楚测试什么类型的信息:数字、字符串、还是一个文件,要么就是一个逻辑关系。当遇到不同的测试类型时自然就有不同的“测试属性”,理解这个测试属性是必须的。不然就不知道从何处下手。   判断的返回值:真、假。   当判断的条件是一...

gulp使用(一)

gulpjs是一个前端构建工具,与gruntjs相比,gulpjs无需写一大堆繁杂的配置参数,API也非常简单,学习起来很容易,而且gulpjs使用的是nodejs中stream来读取和操作数据,其速度更快。如果你还没有使用过前端构建工具,或者觉得gruntjs太难用的话,那就尝试一下gulp吧。   本文导航:   gulp的安装 开始使用gulp gu...

Log4j使用指南

1         概述本文档是针对Log4j日志工具的使用指南。包括:日志介绍、日志工具介绍、Log4j基本使用、Log4j的高级使用、Spring与log4j的集成等。并进行了举例说明。 本文档适合所有Java开发人员。 2         日志介绍存储软件程序、服务或操作系统产生的消息记录的文件。 电脑里的日志是指日志数据可以是有价值的信息宝库,也可...