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服务器当前展现的目录,下图为上传子模块流程图 选择好要上传 ...
随机推荐
- fopen 參数具体解释
fopen fopen(打开文件) 相关函数 open,fclose 表头文件 #include<stdio.h> 定义函数 FILE * fopen(const char * path, ...
- 执行update操作的话,就会报“Connection is read-only. Queries leading to data modification are not allowed”的异常。
我用的是 spring + springmvc + mybatis +mysql. <tx:advice id="txAdvice" transaction-manager= ...
- VS删除未使用的命名空间
把鼠标光变放在Using+命名空间区域,右键——组织 using->移除未使用的 using
- javascript 之 this 用法
参考视频:http://www.imooc.com/video/6430 JavaScript中的this比较灵活,也是让很多初学者摸不到头脑,那么根据在不同的环境下,在同一个函数,不同的调用方式下, ...
- WIN7系统JavaEE(java+tomcat7+Eclipse)环境配
在进行 Java Web环境开发之前,首先要做的第一件事就是搭建开发环境,开发环境搭建成功,接下来便是对整个开发环境进行测试,可以通过编写一个简单的JSP 程序发布到Tomcat应用服务器上运行. 1 ...
- volley三种基本请求图片的方式与Lru的基本使用:正常的加载+含有Lru缓存的加载+Volley控件networkImageview的使用
首先做出全局的请求队列 package com.qg.lizhanqi.myvolleydemo; import android.app.Application; import com.android ...
- UIView的常用方法
bringSubviewToFront: 把指定的子视图移动到顶层 - (void)bringSubviewToFront:(UIView *)view 参数 view 需要移到顶层的视图 conve ...
- java基础学习笔记
Q: What if the main method is declared as private? 如果将主函数声明为私有类型的会怎样? A: The program compile ...
- Linux下安装MySQL步骤
1.下载安装包(这里是32位的): MySQL-client-5.6.13-1.rhel5.i386.rpm MySQL-server-5.6.13-1.rhel5.i386.rpm 2.安装 rpm ...
- HTML5简单入门系列(三)
前言 本篇介绍HTML5支持的Web存储(Web Storage)和HTML 5 应用程序缓存. 客户端存储数据介绍 HTML5 提供了两种在客户端存储数据的新方法: localStorage - 没 ...