C# winfrom 模拟ftp文件管理
从网上找到的非常好用的模拟ftp管理代码,整理了一下,希望对需要的人有帮助
- using System;
- using System.Collections.Generic;
- using System.Text;
- using System.Net;
- using System.IO;
- using System.Windows.Forms;
- namespace ConvertData
- {
- class FtpUpDown
- {
- string ftpServerIP;
- string ftpUserID;
- string ftpPassword;
- FtpWebRequest reqFTP;
- private void Connect(String path)//连接ftp
- {
- // 根据uri创建FtpWebRequest对象
- reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(path));
- // 指定数据传输类型
- reqFTP.UseBinary = true;
- // ftp用户名和密码
- reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
- }
- public FtpUpDown(string ftpServerIP, string ftpUserID, string ftpPassword)
- {
- this.ftpServerIP = ftpServerIP;
- this.ftpUserID = ftpUserID;
- this.ftpPassword = ftpPassword;
- }
- //都调用这个
- private string[] GetFileList(string path, string WRMethods)//上面的代码示例了如何从ftp服务器上获得文件列表
- {
- string[] downloadFiles;
- StringBuilder result = new StringBuilder();
- try
- {
- Connect(path);
- reqFTP.Method = WRMethods;
- WebResponse response = reqFTP.GetResponse();
- StreamReader reader = new StreamReader(response.GetResponseStream(), System.Text.Encoding.Default);//中文文件名
- string line = reader.ReadLine();
- while (line != null)
- {
- result.Append(line);
- result.Append("\n");
- line = reader.ReadLine();
- }
- // to remove the trailing '\n'
- result.Remove(result.ToString().LastIndexOf('\n'), 1);
- reader.Close();
- response.Close();
- return result.ToString().Split('\n');
- }
- catch (Exception ex)
- {
- System.Windows.Forms.MessageBox.Show(ex.Message);
- downloadFiles = null;
- return downloadFiles;
- }
- }
- public string[] GetFileList(string path)//上面的代码示例了如何从ftp服务器上获得文件列表
- {
- return GetFileList("ftp://" + ftpServerIP + "/" + path, WebRequestMethods.Ftp.ListDirectory);
- }
- public string[] GetFileList()//上面的代码示例了如何从ftp服务器上获得文件列表
- {
- return GetFileList("ftp://" + ftpServerIP + "/", WebRequestMethods.Ftp.ListDirectory);
- }
- public void Upload(string filename) //上面的代码实现了从ftp服务器上载文件的功能
- {
- FileInfo fileInf = new FileInfo(filename);
- string uri = "ftp://" + ftpServerIP + "/" + fileInf.Name;
- Connect(uri);//连接
- // 默认为true,连接不会被关闭
- // 在一个命令之后被执行
- reqFTP.KeepAlive = false;
- // 指定执行什么命令
- reqFTP.Method = WebRequestMethods.Ftp.UploadFile;
- // 上传文件时通知服务器文件的大小
- reqFTP.ContentLength = fileInf.Length;
- // 缓冲大小设置为kb
- int buffLength = 2048;
- byte[] buff = new byte[buffLength];
- int contentLen;
- // 打开一个文件流(System.IO.FileStream) 去读上传的文件
- FileStream fs = fileInf.OpenRead();
- try
- {
- // 把上传的文件写入流
- Stream strm = reqFTP.GetRequestStream();
- // 每次读文件流的kb
- contentLen = fs.Read(buff, 0, buffLength);
- // 流内容没有结束
- while (contentLen != 0)
- {
- // 把内容从file stream 写入upload stream
- strm.Write(buff, 0, contentLen);
- contentLen = fs.Read(buff, 0, buffLength);
- }
- // 关闭两个流
- strm.Close();
- fs.Close();
- }
- catch (Exception ex)
- {
- MessageBox.Show(ex.Message, "Upload Error");
- }
- }
- public bool Download(string filePath, string fileName, out string errorinfo)////上面的代码实现了从ftp服务器下载文件的功能
- {
- try
- {
- String onlyFileName = Path.GetFileName(fileName);
- string newFileName = filePath + "\\" + onlyFileName;
- if (File.Exists(newFileName))
- {
- errorinfo = string.Format("本地文件{0}已存在,无法下载", newFileName);
- return false;
- }
- string url = "ftp://" + ftpServerIP + "/" + fileName;
- Connect(url);//连接
- reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
- FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
- Stream ftpStream = response.GetResponseStream();
- long cl = response.ContentLength;
- int bufferSize = 2048;
- int readCount;
- byte[] buffer = new byte[bufferSize];
- readCount = ftpStream.Read(buffer, 0, bufferSize);
- FileStream outputStream = new FileStream(newFileName, FileMode.Create);
- while (readCount > 0)
- {
- outputStream.Write(buffer, 0, readCount);
- readCount = ftpStream.Read(buffer, 0, bufferSize);
- }
- ftpStream.Close();
- outputStream.Close();
- response.Close();
- errorinfo = "";
- return true;
- }
- catch (Exception ex)
- {
- errorinfo = string.Format("因{0},无法下载", ex.Message);
- return false;
- }
- }
- //删除文件
- public void DeleteFileName(string fileName)
- {
- try
- {
- FileInfo fileInf = new FileInfo(fileName);
- string uri = "ftp://" + ftpServerIP + "/" + fileInf.Name;
- Connect(uri);//连接
- // 默认为true,连接不会被关闭
- // 在一个命令之后被执行
- reqFTP.KeepAlive = false;
- // 指定执行什么命令
- reqFTP.Method = WebRequestMethods.Ftp.DeleteFile;
- FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
- response.Close();
- }
- catch (Exception ex)
- {
- MessageBox.Show(ex.Message, "删除错误");
- }
- }
- //创建目录
- public void MakeDir(string dirName)
- {
- try
- {
- string uri = "ftp://" + ftpServerIP + "/" + dirName;
- Connect(uri);//连接
- reqFTP.Method = WebRequestMethods.Ftp.MakeDirectory;
- FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
- response.Close();
- }
- catch (Exception ex)
- {
- MessageBox.Show(ex.Message);
- }
- }
- //删除目录
- public void delDir(string dirName)
- {
- try
- {
- string uri = "ftp://" + ftpServerIP + "/" + dirName;
- Connect(uri);//连接
- reqFTP.Method = WebRequestMethods.Ftp.RemoveDirectory;
- FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
- response.Close();
- }
- catch (Exception ex)
- {
- MessageBox.Show(ex.Message);
- }
- }
- //获得文件大小
- public long GetFileSize(string filename)
- {
- long fileSize = 0;
- try
- {
- FileInfo fileInf = new FileInfo(filename);
- string uri = "ftp://" + ftpServerIP + "/" + fileInf.Name;
- Connect(uri);//连接
- reqFTP.Method = WebRequestMethods.Ftp.GetFileSize;
- FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
- fileSize = response.ContentLength;
- response.Close();
- }
- catch (Exception ex)
- {
- MessageBox.Show(ex.Message);
- }
- return fileSize;
- }
- //文件改名
- public void Rename(string currentFilename, string newFilename)
- {
- try
- {
- FileInfo fileInf = new FileInfo(currentFilename);
- string uri = "ftp://" + ftpServerIP + "/" + fileInf.Name;
- Connect(uri);//连接
- reqFTP.Method = WebRequestMethods.Ftp.Rename;
- reqFTP.RenameTo = newFilename;
- FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
- //Stream ftpStream = response.GetResponseStream();
- //ftpStream.Close();
- response.Close();
- }
- catch (Exception ex)
- {
- MessageBox.Show(ex.Message);
- }
- }
- //获得文件明晰
- public string[] GetFilesDetailList()
- {
- return GetFileList("ftp://" + ftpServerIP + "/", WebRequestMethods.Ftp.ListDirectoryDetails);
- }
- //获得文件明晰
- public string[] GetFilesDetailList(string path)
- {
- return GetFileList("ftp://" + ftpServerIP + "/" + path, WebRequestMethods.Ftp.ListDirectoryDetails);
- }
- }
- }
上面为类,举例证明如何代用
- private void button1_Click(object sender, EventArgs e)//文件上传
- {
- FtpUpDown ftpUpDown = new FtpUpDown("192.168.2.130:21", "wl","123456");
- ftpUpDown.Upload("E:\\other.rar");
- }
- private void button3_Click(object sender, EventArgs e)//修改
- {
- FtpUpDown ftpUpDown = new FtpUpDown("192.168.2.130:21", "wl", "123456");
- ftpUpDown.Rename("张三", "李四");
- }
- private void button4_Click(object sender, EventArgs e)//删除
- {
- FtpUpDown ftpUpDown = new FtpUpDown("192.168.2.130:21", "wl", "123456");
- ftpUpDown.delDir("张三");
- }
- private void button2_Click(object sender, EventArgs e)//添加
- {
- FtpUpDown ftpUpDown = new FtpUpDown("192.168.2.130:21", "wl", "123456");
- ftpUpDown.MakeDir(this.TxT_name.Text);
- }
- //获得ftp文件的文件明晰,还为处理,能够获得所有的文件名称
- FtpUpDown ftpUpDown = new FtpUpDown("192.168.2.130", "wl", "123456");
- string[] str = ftpUpDown.GetFilesDetailList();
- int i = 1;
- foreach (string item in str)
- {
- string[] name = item.Split(' ');
- TxT_name.Text += name[name.Length - 1] + ";";
- i++;
- }
- label1.Text = i.ToString();
C# winfrom 模拟ftp文件管理的更多相关文章
- linux命令-sftp(模拟ftp服务)和scp(文件异地直接复制)
1)sftp sftp是模拟ftp的服务,使用22端口 针对远方服务器主机 (Server) 之行为 变换目录到 /etc/test 或其他目录 cd /etc/testcd PATH 列出目前所在目 ...
- FTP文件管理
因为网站有下载文件需要和网站分离,使用到了FTP管理文件,这里做一个简单的整理. 1.安装FTP 和安装iis一样.全部勾选. 设置站点名称和路径. 设置ip. 身份授权选择所有用户,可以读写. 完成 ...
- linux下模拟FTP服务器(笔记)
要在linux下做一个模仿ftp的小型服务器,后来在百度文库中找到一份算是比较完整的实现,就在原代码一些重要部分上备注自己的理解(可能有误,千万不要轻易相信). 客户端: 客户端要从服务器端中读取数据 ...
- python-TCP模拟ftp文件传输
#!/usr/bin/python #coding=utf-8 #server from socket import* import sys,os def command(): l=[ "W ...
- ftp应用
ftp的基本应用: 下载easyfzs ftp,仿真模拟ftp服务器. 类库: using System; using System.Collections.Generic; using System ...
- python 开发一个支持多用户在线的FTP
### 作者介绍:* author:lzl### 博客地址:* http://www.cnblogs.com/lianzhilei/p/5813986.html### 功能实现 作业:开发一个支持多用 ...
- FTP服务器上删除文件夹失败
很多人都知道:要删除FTP服务器上的文件夹时,必须确保文件夹下面没有其他文件,否则会删除失败! 可是,有些服务器考虑到安全等因素,通常会隐藏以点开始的文件名,例如“.test.txt”.于是,有的坏人 ...
- 基于套接字通信的简单练习(FTP)
本项目基于c/s架构开发(采用套接字通信,使用TCP协议) FTP-Socket"""__author:rianley cheng""" 功 ...
- Java语言实现简单FTP软件------>上传下载管理模块的实现(十一)
1.上传本地文件或文件夹到远程FTP服务器端的功能. 当用户在本地文件列表中选择想要上传的文件后,点击上传按钮,将本机上指定的文件上传到FTP服务器当前展现的目录,下图为上传子模块流程图 选择好要上传 ...
随机推荐
- windows 和linux 同步api对比
初始化临界区 (win) InitializeCriticalSection(RTL_CRITICAL_SECTION &rtl_critial_section) (linux) pthrea ...
- vue 单页面应用实战
1. 为什么要 SPA? SPA: 就是俗称的单页应用(Single Page Web Application). 在移动端,特别是 hybrid 方式的H5应用中,性能问题一直是痛点. 使用 SPA ...
- [转]eclipse下编写android程序突然不会自动生成R.java文件和包的解决办法
原网址 : http://www.cnblogs.com/zdz8207/archive/2012/11/30/eclipse-android-adt-update.html 网上解决方法主要有这几种 ...
- Android ListView使用(非原创)
1.ListView:它以列表的形式展示具体要显示的内容,并且能够根据数据的长度自适应屏幕显示 <LinearLayout xmlns:android="http://schemas. ...
- sqlserver2008 中使用MSXML2.ServerXMLHttp拼装soap调用webservice
要调用的接口方法:UP_ACC_inst_Info(string xml) 接口参数:xml格式的字符串 接口功能:传递人员编号.备注到接口进行更新,接口返回更新结果. 实例: declare @st ...
- ios开发 AFNetworking的基本使用方法
AFNetworking的基本使用方法 什么是GET请求? 如果只是单纯的下载数据, 使用GET请求 什么是POST请求? 特点: 请求的内容不会出现在URL网址中 向服务器发送用户名和密码, 或者 ...
- POJ 2135 Farm Tour (最小费用最大流模板)
题目大意: 给你一个n个农场,有m条道路,起点是1号农场,终点是n号农场,现在要求从1走到n,再从n走到1,要求不走重复路径,求最短路径长度. 算法讨论: 最小费用最大流.我们可以这样建模:既然要求不 ...
- Delphi Length函数
unit Unit1; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms ...
- JQuery阻止表单提交的方法总结 - 使用onsubmit()验证表单并阻止非法提交
方法1:<form onsubmit="javascript:confirm()"> 方法内返回false阻止表单提交 示例:代码检测textarea内填写的长度,未填 ...
- 函数stripslashes去除转义 shopnc 搜索框过滤特殊字符 输入单斜杆会自动转义
如何php是如何处理和过滤特殊字符的呢? 搜索%_显示所有商品:搜索\会在搜索框内叠加\\ 查了一下 magic_quotes_sybase 项开启,反斜线将被去除,但是两个反斜线将会被替换成一个. ...