Ubuntu vsftp搭建和C# Winform FTP操作
来源:互联网 发布:车子天窗有必要吗 知乎 编辑:程序博客网 时间:2024/05/24 05:55
说明:学生作业(个人经验仅供参考):
1. Windows下虚拟机Ubuntu 14.04 搭架vsftp
1.1 查看虚拟机与本机是否能ping通
这里虚拟机和本机网络的连接方式是桥接模式。首先通过ipconfig(windows)、ifconfig(ubuntu)得到机子的ip地址,然后查看是否能够pingt通
windows ping ubuntu
ubuntu ping windows
有些情况下windows能够ping通ubuntu,但是ubuntu ping不通windows,可能是windows的防火墙设置有问题,我找到的解决办法是
允许选中框中的条目
1.2 ubuntu搭建vsftp
在ubuntu上安装vsftp,后面的d代表的是这个程序会在开机的时候就启动直到关机
sudo apt-get install vsftpd
cp etc/vsftpd.conf /home/xxx/Desktop/vsdtpd.conf.backsudo vim vsftpd.conf
之后配置vsftp,这是最关键的部分,配置稍微有问题就会出错
重启ftp
#禁止匿名访问anonymous_enable=NO#接受本地用户local_enable=YES#允许上传write_enable=YES#用户只能访问限制的目录chroot_local_user=YES#设置固定目录,在结尾添加。如果不添加这一行,各用户对应自己的目录,当然这个文件夹自己建local_root=/home/ftp
重启ftp
sudo service vsftpd restart
添加ftp用户名和密码 /home/ftp为我设置的ftp目录,目录设置不一样会530错误+_+||
源自:http://blog.sina.com.cn/s/blog_7880d3350102vvlb.html
sudo useradd -d /home/ftp -M ftp
sudo password ftp参考:
http://www.2cto.com/os/201409/336555.html
2. Winform下对FTP操作
这里附上我使用的ftp操作类,我这里使用递归将FTP目录下的文件和文件名显示在c# treeview中
FTP操作的我是在http://www.cnblogs.com/swtseaman/archive/2011/03/29/1998611.html找的,但是根据项目修改了部分
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Globalization;using System.Windows.Forms;using System.Net;using System.IO;namespace exam4{ class FTPlib { public class FtpWeb { string ftpServerIP; string ftpRemotePath; string ftpUserID; string ftpPassword; string ftpURI; public String FtpURI { get { return ftpURI; } //不留set属性 } /// <summary> /// 连接FTP /// </summary> /// <param name="FtpServerIP">FTP连接地址</param> /// <param name="FtpRemotePath">指定FTP连接成功后的当前目录, 如果不指定即默认为根目录</param> /// <param name="FtpUserID">用户名</param> /// <param name="FtpPassword">密码</param> public FtpWeb(string FtpServerIP, string FtpRemotePath, string FtpUserID, string FtpPassword) { ftpServerIP = FtpServerIP; ftpRemotePath = FtpRemotePath; ftpUserID = FtpUserID; ftpPassword = FtpPassword; ftpURI = ftpServerIP + "/" /*+ ftpRemotePath + "/"*/; } /// <summary> /// 上传 /// </summary> /// <param name="filename"></param> public void Upload(string filename) { FileInfo fileInf = new FileInfo(filename); string uri = ftpURI + fileInf.Name; FtpWebRequest reqFTP; reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri)); reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword); 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 { Stream strm = reqFTP.GetRequestStream(); 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) { Insert_Standard_ErrorLog.Insert("FtpWeb", "Upload Error --> " + ex.Message); } } /// <summary> /// 下载 /// </summary> /// <param name="filePath"></param> /// <param name="fileName"></param> public void Download(string filePath, String path, string fileName) { FtpWebRequest reqFTP; try { FileStream outputStream = new FileStream(filePath + "" + fileName, FileMode.Create); reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI + path)); reqFTP.Method = WebRequestMethods.Ftp.DownloadFile; reqFTP.UseBinary = true; 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); while (readCount > 0) { outputStream.Write(buffer, 0, readCount); readCount = ftpStream.Read(buffer, 0, bufferSize); } ftpStream.Close(); outputStream.Close(); response.Close(); } catch (Exception ex) { Insert_Standard_ErrorLog.Insert("FtpWeb", "Download Error --> " + ex.Message); } } /// <summary> /// 删除文件 /// </summary> /// <param name="fileName"></param> public void Delete(string fileName) { try { string uri = ftpURI + fileName; FtpWebRequest reqFTP; reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri)); reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword); reqFTP.KeepAlive = false; reqFTP.Method = WebRequestMethods.Ftp.DeleteFile; string result = String.Empty; FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse(); long size = response.ContentLength; Stream datastream = response.GetResponseStream(); StreamReader sr = new StreamReader(datastream); result = sr.ReadToEnd(); sr.Close(); datastream.Close(); response.Close(); } catch (Exception ex) { Insert_Standard_ErrorLog.Insert("FtpWeb", "Delete Error --> " + ex.Message + " 文件名:" + fileName); } } /// <summary> /// 删除文件夹 /// </summary> /// <param name="folderName"></param> public void RemoveDirectory(string folderName) { try { string uri = ftpURI + folderName; FtpWebRequest reqFTP; reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri)); reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword); reqFTP.KeepAlive = false; reqFTP.Method = WebRequestMethods.Ftp.RemoveDirectory; string result = String.Empty; FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse(); long size = response.ContentLength; Stream datastream = response.GetResponseStream(); StreamReader sr = new StreamReader(datastream); result = sr.ReadToEnd(); sr.Close(); datastream.Close(); response.Close(); } catch (Exception ex) { Insert_Standard_ErrorLog.Insert("FtpWeb", "Delete Error --> " + ex.Message + " 文件名:" + folderName); } } /// <summary> /// 获取当前目录下明细(包含文件和文件夹) /// </summary> /// <returns></returns> public string[] GetFilesDetailList(String filename) { string[] downloadFiles; try { StringBuilder result = new StringBuilder(); FtpWebRequest ftp; ftp = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI+filename)); ftp.Credentials = new NetworkCredential(ftpUserID, ftpPassword); ftp.Method = WebRequestMethods.Ftp.ListDirectoryDetails; WebResponse response = ftp.GetResponse(); StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.Default); //while (reader.Read() > 0) //{ //} string line = reader.ReadLine(); //line = reader.ReadLine(); //line = reader.ReadLine(); while (line != null) { result.Append(line); result.Append("\n"); line = reader.ReadLine(); } result.Remove(result.ToString().LastIndexOf("\n"), 1); reader.Close(); response.Close(); return result.ToString().Split('\n'); } catch (Exception ex) { downloadFiles = null; //MessageBox.Show("连接FTP获取根目录下文件列表出错了", "ERROR", MessageBoxButtons.OK, // MessageBoxIcon.Error); Insert_Standard_ErrorLog.Insert("FtpWeb", "GetFilesDetailList Error --> " + ex.Message); return downloadFiles; } } /// <summary> /// 获取当前目录下文件列表(仅文件) /// </summary> /// <returns></returns> public string[] GetFileList(string mask) { string[] downloadFiles; StringBuilder result = new StringBuilder(); FtpWebRequest reqFTP; try { reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI)); reqFTP.UseBinary = true; reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword); reqFTP.Method = WebRequestMethods.Ftp.ListDirectory; WebResponse response = reqFTP.GetResponse(); StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.Default); string line = reader.ReadLine(); while (line != null) { if (mask.Trim() != string.Empty && mask.Trim() != "*.*") { string mask_ = mask.Substring(0, mask.IndexOf("*")); if (line.Substring(0, mask_.Length) == mask_) { result.Append(line); result.Append("\n"); } } else { result.Append(line); result.Append("\n"); } line = reader.ReadLine(); } result.Remove(result.ToString().LastIndexOf('\n'), 1); reader.Close(); response.Close(); return result.ToString().Split('\n'); } catch (Exception ex) { downloadFiles = null; if (ex.Message.Trim() != "远程服务器返回错误: (550) 文件不可用(例如,未找到文件,无法访问文件)。") { Insert_Standard_ErrorLog.Insert("FtpWeb", "GetFileList Error --> " + ex.Message.ToString()); } return downloadFiles; } } /// <summary> /// 获取当前目录下所有的文件夹列表(仅文件夹) /// </summary> /// <returns></returns> public string[] GetDirectoryList(String filename) { string[] drectory = GetFilesDetailList(filename); string m = string.Empty; foreach (string str in drectory) { int dirPos = str.IndexOf("<DIR>"); if (dirPos > 0) { /*判断 Windows 风格*/ m += str.Substring(dirPos + 5).Trim() + "\n"; } else if (str.Trim().Substring(0, 1).ToUpper() == "D") { /*判断 Unix 风格*/ string dir = str.Substring(56).Trim(); if (dir != "." && dir != "..") { m += dir + "\n"; } } } char[] n = new char[] { '\n' }; return m.Split(n); } /// <summary> /// 判断当前目录下指定的子目录是否存在 /// </summary> /// <param name="RemoteDirectoryName">指定的目录名</param> public bool DirectoryExist(string RemoteDirectoryName) { string[] dirList = GetDirectoryList(""); foreach (string str in dirList) { if (str.Trim() == RemoteDirectoryName.Trim()) { return true; } } return false; } /// <summary> /// 判断当前目录下指定的文件是否存在 /// </summary> /// <param name="RemoteFileName">远程文件名</param> public bool FileExist(string RemoteFileName) { string[] fileList = GetFileList("*.*"); foreach (string str in fileList) { if (str.Trim() == RemoteFileName.Trim()) { return true; } } return false; } /// <summary> /// 创建文件夹 /// </summary> /// <param name="dirName"></param> public void MakeDir(string dirName) { FtpWebRequest reqFTP; try { // dirName = name of the directory to create. reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI + dirName)); reqFTP.Method = WebRequestMethods.Ftp.MakeDirectory; reqFTP.UseBinary = true; reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword); FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse(); Stream ftpStream = response.GetResponseStream(); ftpStream.Close(); response.Close(); } catch (Exception ex) { Insert_Standard_ErrorLog.Insert("FtpWeb", "MakeDir Error --> " + ex.Message); } } /// <summary> /// 获取指定文件大小 /// </summary> /// <param name="filename"></param> /// <returns></returns> public long GetFileSize(string filename) { FtpWebRequest reqFTP; long fileSize = 0; try { reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI + filename)); reqFTP.Method = WebRequestMethods.Ftp.GetFileSize; reqFTP.UseBinary = true; reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword); FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse(); Stream ftpStream = response.GetResponseStream(); fileSize = response.ContentLength; ftpStream.Close(); response.Close(); } catch (Exception ex) { Insert_Standard_ErrorLog.Insert("FtpWeb", "GetFileSize Error --> " + ex.Message); } return fileSize; } /// <summary> /// 改名 /// </summary> /// <param name="currentFilename"></param> /// <param name="newFilename"></param> public void ReName(string currentFilename, string newFilename) { FtpWebRequest reqFTP; try { reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI + currentFilename)); reqFTP.Method = WebRequestMethods.Ftp.Rename; reqFTP.RenameTo = newFilename; reqFTP.UseBinary = true; reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword); FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse(); Stream ftpStream = response.GetResponseStream(); ftpStream.Close(); response.Close(); } catch (Exception ex) { Insert_Standard_ErrorLog.Insert("FtpWeb", "ReName Error --> " + ex.Message); } } /// <summary> /// 移动文件 /// </summary> /// <param name="currentFilename"></param> /// <param name="newFilename"></param> public void MovieFile(string currentFilename, string newDirectory) { ReName(currentFilename, newDirectory); } /// <summary> /// 切换当前目录 /// </summary> /// <param name="DirectoryName"></param> /// <param name="IsRoot">true 绝对路径 false 相对路径</param> public void GotoDirectory(string DirectoryName, bool IsRoot) { if (IsRoot) { ftpRemotePath = DirectoryName; } else { ftpRemotePath += DirectoryName + "/"; } ftpURI = "ftp://" + ftpServerIP + "/" + ftpRemotePath + "/"; } /// <summary> /// 删除订单目录 /// </summary> /// <param name="ftpServerIP">FTP 主机地址</param> /// <param name="folderToDelete">FTP 用户名</param> /// <param name="ftpUserID">FTP 用户名</param> /// <param name="ftpPassword">FTP 密码</param> public static void DeleteOrderDirectory(string ftpServerIP, string folderToDelete, string ftpUserID, string ftpPassword) { try { if (!string.IsNullOrEmpty(ftpServerIP) && !string.IsNullOrEmpty(folderToDelete) && !string.IsNullOrEmpty(ftpUserID) && !string.IsNullOrEmpty(ftpPassword)) { FtpWeb fw = new FtpWeb(ftpServerIP, folderToDelete, ftpUserID, ftpPassword); //进入订单目录 fw.GotoDirectory(folderToDelete, true); //获取规格目录 string[] folders = fw.GetDirectoryList(""); foreach (string folder in folders) { if (!string.IsNullOrEmpty(folder) || folder != "") { //进入订单目录 string subFolder = folderToDelete + "/" + folder; fw.GotoDirectory(subFolder, true); //获取文件列表 string[] files = fw.GetFileList("*.*"); if (files != null) { //删除文件 foreach (string file in files) { fw.Delete(file); } } //删除冲印规格文件夹 fw.GotoDirectory(folderToDelete, true); fw.RemoveDirectory(folder); } } //删除订单文件夹 string parentFolder = folderToDelete.Remove(folderToDelete.LastIndexOf('/')); string orderFolder = folderToDelete.Substring(folderToDelete.LastIndexOf('/') + 1); fw.GotoDirectory(parentFolder, true); fw.RemoveDirectory(orderFolder); } else { throw new Exception("FTP 及路径不能为空!"); } } catch (Exception ex) { throw new Exception("删除订单时发生错误,错误信息为:" + ex.Message); } } } public class Insert_Standard_ErrorLog { public static void Insert(string x, string y) { } } }}原作者GetDirectoryList()截取字符的位置应该是56不是54
递归
TreeNode rootnode = GetFileTree();treeView1.Nodes.Add(rootnode);
//创建文件树结构 public TreeNode GetFileTree() { TreeNode RootNode = new TreeNode(); RootNode.Text = "FTP file"; RootNode.ImageIndex = 1; RootNode.SelectedImageIndex = 1; String[] FTPfile_detail = FTPserver.GetFilesDetailList(""); foreach (String temp in FTPfile_detail) { //对于是文件夹的情况 if (temp.Trim().Substring(0, 1).ToUpper() == "D") { TreeNode node = new TreeNode(); node.Text = temp.Trim().Substring(56); node.ImageIndex = 1; node.SelectedImageIndex = 1; Create_filemap(ref node, "", temp.Trim().Substring(56)); RootNode.Nodes.Add(node); } else //对于文件的情况 { TreeNode node = new TreeNode(); node.Text = temp.Trim().Substring(56); node.ImageIndex = 0; node.SelectedImageIndex = 0; RootNode.Nodes.Add(node); } } return RootNode; } //递归调用产生文件目录 public bool Create_filemap(ref TreeNode sub_rootnode, String current_path, String folder_name) { if (null == sub_rootnode) { MessageBox.Show("传递的树节点为空", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error); return false; } current_path = current_path + folder_name + "/"; String[] FTPfile_detail = FTPserver.GetFilesDetailList(current_path); if(null != FTPfile_detail) { foreach (String temp in FTPfile_detail) { //对于是文件夹的情况 if (temp.Trim().Substring(0, 1).ToUpper() == "D") { TreeNode node = new TreeNode(); node.Text = temp.Trim().Substring(56); node.ImageIndex = 1; node.SelectedImageIndex = 1; Create_filemap(ref node, current_path, temp.Trim().Substring(56)); sub_rootnode.Nodes.Add(node); } else //对于文件的情况 { TreeNode node = new TreeNode(); node.Text = temp.Trim().Substring(56); node.ImageIndex = 0; node.SelectedImageIndex = 0; sub_rootnode.Nodes.Add(node); } } } return true; }
0 0
- Ubuntu vsftp搭建和C# Winform FTP操作
- [转]Ubuntu 用VSFTP搭建FTP服务器
- Ubuntu 用VSFTP搭建FTP服务器
- Ubuntu 用VSFTP搭建FTP服务器
- Ubuntu 用VSFTP搭建FTP服务器
- Python ftp操作之一-------linux vsftp搭建
- ubuntu 12.04搭建vsftp和Windows xp搭建IIS ftp和windows打印机共享
- ubuntu 安装 ftp vsftp
- Ubuntu——用VSFTP搭建FTP服务器(2)
- Ubuntu vsftp的搭建和配置(一)
- Ubuntu vsftp的搭建和配置(二)
- ubuntu搭建vsftp服务器
- ubuntu 下搭建vsftp
- ubuntu 16.04 搭建vsftp
- Ubuntu 16.04 VSFTP服务器搭建
- Ubuntu 16.04 VSFTP服务器搭建
- Ubuntu 16.04 VSFTP服务器搭建
- Linux Ubuntu搭建vsftp服务器
- java并发编程(四)--守护线程与线程阻塞的四种情况
- C++类和结构体的区别
- Linux文件特殊权限——SetUID、SetGID、Sticky BIT
- 手机开发实战160——EXIF格式介绍1
- java.util.zip.ZipException: duplicate entry: com/nineoldandroids/animation/Animator$AnimatorListener
- Ubuntu vsftp搭建和C# Winform FTP操作
- centos mysql 安装与配置
- 手机开发实战161——EXIF格式介绍2
- 二分搜索
- SPS、PPS、IDR
- matlab读取stl文件
- writeup hitcon-ctf-2014/stkof
- poj 2418 map入门(统计单词频率)
- 手机开发实战162——EXIF格式介绍3