C#下的FTP上传和下载

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.IO;

namespace FTP_Up_Down
{
    public partial class FTP : Form
    {
        public FTP()
        {
            InitializeComponent();
        }
        //定义字段
        string ftpServerIP;//服务器IP

        private void FTP_Load(object sender, EventArgs e)
        {
            ftpServerIP = "127.0.0.1";
            this.textBox_IP.Text = ftpServerIP;
        }

        //显示服务器已存在的文件
        private void button_ShowList_Click(object sender, EventArgs e)
        {   
            this.button_ShowList.Text="刷新";
            string[] filenames = GetFilesList();//调用“文件列表”
            listBox_FlieList.Items.Clear();
            try
            {
                foreach (string filename in filenames)
                {
                    listBox_FlieList.Items.Add(filename);
                }
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.Message);
                return;
            }
        }

        //文件列表
        public string[] GetFilesList()
        {
            string[] downloadFiles;          
            StringBuilder result = new StringBuilder();//定义一个可变字符串字段      
            FtpWebRequest reqFTP;//实现文件传输协议(FTP)客户端
            try
            {       
                reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + ftpServerIP + "/"));//为指定的URI创建FtpWebRequest实例      
                reqFTP.UseBinary = true;    //采用二进制数据类型传输    
                reqFTP.Method = WebRequestMethods.Ftp.ListDirectory; //获取FTP服务器上的文件的简短列表   
                WebResponse response = reqFTP.GetResponse();    //提供来自URI的响应    
                StreamReader reader = new StreamReader(response.GetResponseStream());  //从字节流中读取字符       
                string line = reader.ReadLine(); //持续读取文件名以便列表显示
                while (line != null)
                {
                    result.Append(line);
                    result.Append("\n");
                    line = reader.ReadLine();
                }           
                result.Remove(result.ToString().LastIndexOf('\n'), 1); //去除最后一个多余的换行符('\n')
                reader.Close();//关闭读文件流
                response.Close();   
                return result.ToString().Split('\n'); //返回文件名列表结果
            }
            catch (Exception ex)
            {
                System.Windows.Forms.MessageBox.Show(ex.Message);
                downloadFiles = null;
                return downloadFiles;
            }
        }

        //上传
        private void button_Up_Click(object sender, EventArgs e)
        {
            OpenFileDialog opFilDlg = new OpenFileDialog();
            if (opFilDlg.ShowDialog() == DialogResult.OK)
            {     
                UpLoad(opFilDlg.FileName); //调用“上传文件”     
                string[] filenames = GetFilesList(); //刷新文件名列表
                listBox_FlieList.Items.Clear();
                foreach (string filename in filenames)
                {
                    listBox_FlieList.Items.Add(filename);
                }
                MessageBox.Show("文件上传结束。");
            }
        }

        //上传文件
        private void UpLoad(string filename)
        {
            FileInfo fileInf = new FileInfo(filename);  
            FtpWebRequest reqFTP;   //实现文件传输协议(FTP)客户端
            reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + ftpServerIP + "/" + fileInf.Name));//为指定的URI创建FtpWebRequest对象      
            reqFTP.KeepAlive = false;  //默认为true,在一个命令之后被执行连接不会被关闭
            reqFTP.Method = WebRequestMethods.Ftp.UploadFile;//指定执行上传命令
            reqFTP.UseBinary = true;  //指定数据传输类型(二进制)
            reqFTP.ContentLength = fileInf.Length;//上传文件时通知服务器文件的大小
            int buffLength = 2048; //缓冲大小设置为2kb
            byte[] buff = new byte[buffLength];
            int contentLen;     
            FileStream fs = fileInf.OpenRead(); //打开一个文件流 (System.IO.FileStream) 来读上传的文件
            try
            {
                Stream strm = reqFTP.GetRequestStream();//检索用于向FTP服务器上载数据的流
                contentLen = fs.Read(buff, 0, buffLength); //每次从文件流中读入2kb(缓冲大小)
                while (contentLen != 0)  //持续进行文件流的读写,直至全部结束
                {         
                    strm.Write(buff, 0, contentLen); //将所读取的文件流写入到上传流的字节序列
                    contentLen = fs.Read(buff, 0, buffLength);
                }      
                strm.Close(); //关闭文件流和上传流
                fs.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "文件上传出错。");
            }
        }

        //下载
        private void button_Down_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog fldDlg = new FolderBrowserDialog();
            if (listBox_FlieList.Text.Trim().Length > 0)
            {
                if (fldDlg.ShowDialog() == DialogResult.OK)
                {             
                    DownLoad(fldDlg.SelectedPath, listBox_FlieList.Text.Trim());//调用“下载文件”
                }
                MessageBox.Show("文件下载结束。");
            }
            else
            {
                MessageBox.Show("请选择需要下载的文件。");
            }
        }

        //下载文件
        private void DownLoad(string filePath, string fileName)
        {
            FtpWebRequest reqFTP;
            try
            {
                //设置文件下载后的保存路径(文件夹):filePath
                //命名下载后的文件名(可与原文件名不同):fileName
                FileStream outputStream = new FileStream(filePath + "\\" + fileName, FileMode.Create);
                reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + ftpServerIP + "/" + fileName));
                //指定执行下载命令
                reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
                reqFTP.UseBinary = true;          
                FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse(); //返回FTP服务器响应         
                Stream ftpStream = response.GetResponseStream();//检索从FTP服务器上发送的响应数据的流               
                long cl = response.ContentLength;//获取从FTP服务器上接收的数据的长度
                int bufferSize = 2048;
                int readCount;
                byte[] buffer = new byte[bufferSize];              
                readCount = ftpStream.Read(buffer, 0, bufferSize);//从当前流读取字节序列,并将此流中的位置提升读取的字节数
                while (readCount > 0)
                {          
                    outputStream.Write(buffer, 0, readCount);//使用从缓冲区中读取的数据,将字节块写入该流
                    readCount = ftpStream.Read(buffer, 0, bufferSize);
                }
                //关闭两个流
                ftpStream.Close();
                outputStream.Close();
                response.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
    }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值