C# winfrom 模拟ftp文件管理实现代码
发布时间:2023-07-15 16:29:48
标签:模拟ftp文件管理,winfrom
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();
0
投稿
猜你喜欢
- 今天给大家介绍一下SpringBoot中JPA的一些常用操作,例如:增删改查、分页、排序、事务操作等功能。下面先来介绍一下JPA中一些常用的
- requestFoucs();无效。requestFoucsFromTouch();无效。webview.setTouchListener;
- 目录概述认证方式基础认证Auth用户名密码认证Bearer Token 认证配置超时生成 RequestConfig设置超时时间概述日常工作
- 近日于LeetCode看题遇1114 按序打印,获悉一解法使用了Semaphore,顺势研究,记心得于此。此解视Semaphore为锁,以保
- 这篇会深化View拖拽实例,利用Flutter Animation、插值器以及AnimatedBuilder教大家实现带动画的抽屉效果。先来
- 1、取得控制台应用程序的根目录方法方法1、Environment.CurrentDirectory 取得或设置当前工作目录的完整限定路径方法
- Android Build类的详解及简单实例一、类结构:java.lang.Object? android.os.Build二、类概述:从系
- 好久没有做web了,JSON目前比较流行,闲得没事,所以动手试试将对象序列化为JSON字符(尽管DotNet Framework
- 本文实例讲述了C#启动进程的几种常用方法。分享给大家供大家参考。具体如下:1.启动子进程,不等待子进程结束private void simp
- 1、右值1.1 简介首先区分一下左右值:左值是指存储在内存中、有明确存储地址(可取地址)的数据;右值是指可以提供数据值的数据(不可取地址)如
- [LeetCode] 159. Longest Substring with At Most Two Distinct Characters
- 1. 并行和并发有什么区别?并行:多个处理器或多核处理器同时处理多个任务。并发:多个任务在同一个 CPU 核上,按细分的时间片轮流(交替)执
- 一、Flutter代码的启动起点我们在多数的业务场景下,使用的都是FlutterActivity、FlutterFragment。在在背后,
- 在类中自定义的“函数”称为“方法”,由于C#是完全面向对象的
- 本文实例为大家分享了Flutter自定义圆盘取色器的具体代码,供大家参考,具体内容如下下面展示一些 内联代码片。圆盘取色器效果图完整代码im
- 本文实例为大家分享了Android实现支付宝支付密码输入界面的具体代码,供大家参考,具体内容如下效果图:主要代码:import java.u
- 大致分为以下几个方面:一些查询指令整理使用SQL语句进行特殊查询检测表字段是否存在数据库升级数据库表字段赋初始值一、查询指令整理1.链式执行
- 一、整体设计1、需求分析池化技术是计算机中的一种设计模式,内存池是常见的池化技术之一,它能够有效的提高内存的申请和释放效率以及内存碎片等问题
- 声明:下面的实例全部在linux下尝试,window下未尝试。有兴趣者可以试一下。文章针c初学者。c语言的强符号和弱符号是c初学者经常容易犯
- 前言目前正在做的项目,为了增加用户的体验度,准备增加一些动画效果,其中底部栏中间按钮的点击事件参考了闲鱼的动效,便在此基础上仿写了该动效,并