FTP网络通信程序设计

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
//添加命名空间引用
using System.Net;
using System.IO;

namespace FTP网络通信程序设计
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        string ftpServerIP;
        string ftpUserID;
        string ftpPassword;

        private void Form1_Load(object sender, EventArgs e)
        {
            ftpServerIP = "127.0.0.1";
            ftpUserID = "anonymous";
            textBoxIPAddress.Text = ftpServerIP;
            textBoxUserName.Text = ftpUserID;
            textBoxPassword.Text = ftpPassword;
        }

        private void textBoxPassword_TextChanged(object sender, EventArgs e)
        {
            buttonOK.Enabled = true;
        }

        private void textBoxUserName_TextChanged(object sender, EventArgs e)
        {
            buttonOK.Enabled = true;
        }

        private void buttonOK_Click(object sender, EventArgs e)
        {
            ftpServerIP = textBoxIPAddress.Text.Trim();
            ftpUserID = textBoxUserName.Text.Trim();
            ftpPassword = textBoxPassword.Text.Trim();
            string[] filenames = GetFilesList();
            listBoxFiles.Items.Clear();
            try
            {
                foreach (string filename in filenames)
                {
                    listBoxFiles.Items.Add(filename);
                }
            }
            catch
            {
                return;
            }
        }
        public string[] GetFilesList()
        {
            string[] downloadFiles;
            StringBuilder result = new StringBuilder();
            //实现文件传输协议客户端
            FtpWebRequest reqFTP;
            try
            {
                reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + ftpServerIP + "/"));
                reqFTP.UseBinary = true;//采用二进制数据类型传输
                //获取与FTP服务器通信的凭据
                reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
                //获取FTP服务器上的文件的简短列表
                reqFTP.Method = WebRequestMethods.Ftp.ListDirectory;
                //提供来自URI的响应
                WebResponse response = reqFTP.GetResponse();
                //从字节流中读取字符
                StreamReader reader = new StreamReader(response.GetResponseStream());
                string line = reader.ReadLine();
                bool flag = false;
                while (line != null)
                {
                    if (flag) result.Append("\n");
                    result.Append(line);
                    flag = true;
                    line = reader.ReadLine();
                }
                //去除最后一个多余的换行符
                //if (result.Length == 0) return null;
                //result.Remove(result.ToString().LastIndexOf('\n'), 1);
                reader.Close();
                response.Close();
                return result.ToString().Split('\n');
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.Message);
                downloadFiles = null;
                return downloadFiles;
            }
        }

        private void buttonUPload_Click(object sender, EventArgs e)
        {
            OpenFileDialog opfildlg = new OpenFileDialog();
            if (opfildlg.ShowDialog() == DialogResult.OK)
            {
                Upload(opfildlg.FileName);
                string[] filenames = GetFilesList();
                listBoxFiles.Items.Clear();
                foreach (string file in filenames)
                    listBoxFiles.Items.Add(file);
                MessageBox.Show("文件上传完毕!!!");
            }
        }

        private void Upload(string filename)
        {
            FileInfo fileinf = new FileInfo(filename);
            //实现文件传输协议客户端
            FtpWebRequest reqFTP;
            //为指定的URI创建FtpWebRequest对象
            reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + ftpServerIP + "/" + fileinf.Name));
            //设置用于ftp服务器通信的凭据
            reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
            //默认为TRUE,在一个命令之后被执行,连接不会关闭
            reqFTP.KeepAlive = false;
            //指定执行上传命令
            reqFTP.Method = WebRequestMethods.Ftp.UploadFile;
            reqFTP.UseBinary = true;
            reqFTP.ContentLength = fileinf.Length;
            int bufflength = 2048;
            byte[] buff = new byte[bufflength];
            int contentLen;
            FileStream fs = fileinf.OpenRead();
            try
            {
                //检索用于向FTP服务器上载数据的流
                Stream strm = reqFTP.GetRequestStream();
                //每次从文件流中读入2KB
                contentLen = fs.Read(buff, 0, bufflength);
                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 buttonDownLoad_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog flddlg = new FolderBrowserDialog();
            if (listBoxFiles.Text.Trim().Length > 0)
            {
                if (flddlg.ShowDialog() == DialogResult.OK)
                {
                    Download(flddlg.SelectedPath, listBoxFiles.Text.Trim());
                }
                MessageBox.Show("文件下载结束。");
            }
            else
            {
                MessageBox.Show("请选择需要下载的文件!!");
            }
        }

        private void Download(string filepath, string filename)
        {
            FtpWebRequest reqFTP;
            try
            {
                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;
                reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
                //返回FTP服务器响应
                FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
                //检索从FTP服务器上发送的响应数据的流
                Stream ftpStream = response.GetResponseStream();
                //获取从FTP服务器上接收的数据的长度
                long cl = response.ContentLength;
                int buffersize = 2048;
                int readcount;
                byte[] buffer = new byte[buffersize];
                //从当前流读取字节序列,并将此流中的位置提升读取的字节数
                readcount = ftpStream.Read(buffer, 0, buffersize);
                while (readcount > 0)
                {
                    outputstream.Write(buffer, 0, buffersize);
                    readcount = ftpStream.Read(buffer, 0, buffersize);
                }
                //关闭两个数据流
                ftpStream.Close();
                outputstream.Close();
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值