ftp上传新文件删除旧文件方法

合集下载

tftp命令用法

tftp命令用法

tftp命令用法TFTP(TrivialFileTransferProtocol)是一种简单文件传输协议,用于在计算机网络之间传输文件。

TFTP提供了一种简单的文件传输,不需要复杂的登录和认证过程即可实现文件传输。

TFTP运行在UDP协议之上,所以它的传输速度要比TCP/IP的传输速度慢。

TFTP最初是由网络设备厂商研发的一种文件传输协议,以解决在网络管理中的文件传输问题。

该协议的优势在于它可以节省其他文件传输协议需要消耗的资源,如登录认证和验证等。

因此,TFTP在网络管理方面比较流行。

《TFTP命令用法》TFTP命令可以用来从服务器上复制文件、从服务器上删除文件、上传文件、以及更改文件大小。

TFTP命令主要有以下几种:get:从远程服务器复制一个文件put:将文件上传到远程服务器del:从远程服务器删除一个文件rename:更改文件名dir:列出远程服务器上的文件mkdir:在远程服务器上创建一个文件夹rmdir:在远程服务器上删除一个文件夹modify:修改文件大小dir -R:列出远程服务器上的文件及子文件夹TFTP命令的使用需要指定一些参数,这些参数包括:-a:如果指定,则传输文件时不检查权限-s:指定使用字符模式传输文件-b:指定使用块模式传输文件-t:指定传输的文件类型,可选值有文本文件和二进制文件-f:指定本地文件名-r:指定远程文件名-l:指定文件大小关于TFTP命令的使用,还有一些其他可选参数,可以使用help 命令查看详细信息。

TFTP具有很多优点,占用资源少,不需要登录和认证,可以实现简单快速的文件传输。

但是,由于它运行在UDP层上,传输速度比TCP/IP慢,也不适合传输大文件和跨越网络的文件传输。

此外,TFTP 服务不支持多用户,不支持加密传输,也无法提供可靠的数据传输,因此对于安全性要求较高的文件传输,不太合适。

TFTP命令的使用简单,但是需要掌握一定的参数,可以提供准确的指令,来实现期望的文件传输。

ftp协议使用方法

ftp协议使用方法

ftp协议使用方法FTP协议使用方法什么是FTP协议FTP协议(File Transfer Protocol)是一种用于在网络上传输文件的通信协议。

它使用客户端-服务器模式,在客户端和服务器之间进行文件的传输和共享。

FTP的工作流程1.建立连接:客户端通过输入服务器的IP地址或域名,与服务器建立TCP连接。

2.身份认证:客户端提供用户名和密码,以验证其身份。

3.导航文件系统:客户端可以浏览服务器上的文件和目录。

4.传输文件:客户端可以上传、下载、删除文件。

5.断开连接:当文件传输完成后,客户端可以断开与服务器的连接。

FTP的使用方法以下是使用FTP协议进行文件传输的方法:•下载文件:客户端通过输入命令get <文件名>或mget *来下载服务器上的文件。

客户端也可以指定本地路径来保存文件。

•上传文件:客户端通过输入命令put <文件名>或mput *来上传本地文件到服务器。

客户端也可以指定服务器上的路径来保存文件。

•列出文件和目录:客户端通过输入命令ls或dir来列出当前服务器上的文件和目录。

客户端也可以通过输入路径来列出指定目录下的文件和目录。

•创建目录:客户端通过输入命令mkdir <目录名>来在服务器上创建新目录。

•删除文件和目录:客户端通过输入命令delete <文件名>或rmdir <目录名>来删除服务器上的文件和目录。

•切换目录:客户端通过输入命令cd <目录名>来切换服务器上的目录。

•重命名文件和目录:客户端通过输入命令rename <原文件名> <新文件名>来重命名服务器上的文件和目录。

客户端软件推荐以下是一些常用的FTP客户端软件:•FileZilla:开源的跨平台FTP客户端软件。

•WinSCP:适用于Windows的免费FTP和SFTP客户端软件。

•Cyberduck:适用于Windows和macOS的免费FTP和SFTP客户端软件。

复制文件后删除原文件的批处理命令

复制文件后删除原文件的批处理命令

一、概述在日常工作中,经常会遇到需要将文件进行复制,并且需要删除原文件的情况。

这种操作在计算机领域中十分常见,因此我们需要一种高效且安全的方法来实现这一操作。

在Windows操作系统中,可以通过批处理命令来批量执行文件复制和删除操作,从而提高工作效率。

本文将介绍如何使用批处理命令来复制文件并删除原文件,以及一些注意事项和常见问题的处理方法。

二、批处理命令介绍1. 批处理命令是一种可以一次性执行多条指令的脚本文件,它可以帮助我们简化重复性的操作,并提高工作效率。

在Windows操作系统中,批处理命令的文件后缀通常为“.bat”。

2. 使用批处理命令可以方便地进行文件的复制和删除操作,从而节省时间和精力。

通过编写一些简单的脚本,即可实现对文件进行自动化处理。

三、复制文件并删除原文件的批处理命令1. 复制文件要使用批处理命令进行文件复制,可以使用“copy”命令。

该命令的基本语法如下:copy <源文件路径> <目标文件路径>其中,“<源文件路径>”表示需要复制的文件的路径,“<目标文件路径>”表示将要复制到的目标路径。

例如:copy C:\source\file.txt D:\destination\file.txt2. 删除原文件要使用批处理命令进行文件删除,可以使用“del”命令。

该命令的基本语法如下:del <文件路径>其中,“<文件路径>”表示需要删除的文件的路径。

例如:del C:\source\file.txt3. 结合使用要实现复制文件并删除原文件的操作,可以将复制和删除命令结合起来,放在同一个批处理文件中。

编写一个名为“copy_and_remove.bat”的批处理文件,内容如下:copy C:\source\file.txt D:\destination\file.txtdel C:\source\file.txt保存该批处理文件后,双击运行即可实现先复制文件,然后删除原文件的操作。

ftpclient方法

ftpclient方法

ftpclient方法FTPClient方法是一种用于实现FTP(File Transfer Protocol,文件传输协议)客户端的方法。

通过使用FTPClient方法,我们可以实现与FTP服务器的连接、文件上传、文件下载、文件删除等操作。

下面将详细介绍FTPClient方法的使用。

一、连接FTP服务器在使用FTPClient方法进行文件传输之前,首先需要与FTP服务器建立连接。

可以通过以下代码实现与FTP服务器的连接:```javaFTPClient ftpClient = new FTPClient();ftpClient.connect(server, port);ftpClient.login(username, password);```其中,server是FTP服务器的IP地址,port是FTP服务器的端口号,username和password分别是登录FTP服务器的用户名和密码。

二、上传文件至FTP服务器使用FTPClient方法可以方便地将本地文件上传至FTP服务器。

可以通过以下代码实现文件上传:```javaFile file = new File(localFilePath);InputStream inputStream = new FileInputStream(file);ftpClient.storeFile(remoteFilePath, inputStream);```其中,localFilePath是本地文件的路径,remoteFilePath是上传至FTP服务器后的文件路径。

三、从FTP服务器下载文件使用FTPClient方法可以方便地从FTP服务器下载文件。

可以通过以下代码实现文件下载:```javaOutputStream outputStream = new FileOutputStream(localFilePath);ftpClient.retrieveFile(remoteFilePath, outputStream);```其中,localFilePath是文件下载后保存的本地路径,remoteFilePath是FTP服务器上待下载文件的路径。

ftp文件操作类(上传、下载、删除、创建、重命名、获取目录中的所有文件)

ftp文件操作类(上传、下载、删除、创建、重命名、获取目录中的所有文件)

ftp⽂件操作类(上传、下载、删除、创建、重命名、获取⽬录中的所有⽂件)ftp⽂件操作类1using System;2using System.Collections.Generic;3using System.Linq;4using System.Text;5using ;6using System.IO;7using System.Data;8using ponentModel;9using System.Windows.Forms;10using System.Text.RegularExpressions;11using System.Globalization;12using System.Collections;1314namespace ESIMRobot15 {16#region⽂件信息结构17public struct FileStruct18 {19public string Flags;20public string Owner;21public string Group;22public bool IsDirectory;23public DateTime CreateTime;24public string Name;25 }26public enum FileListStyle27 {28 UnixStyle,29 WindowsStyle,30 Unknown31 }32#endregion3334///<summary>35/// ftp⽂件上传、下载操作类36///</summary>37public class FTPHelper38 {39private string ftpServerURL;40private string ftpUser;41private string ftpPassWord;4243///<summary>44///45///</summary>46///<param name="ftpServerURL">ftp服务器路径</param>47///<param name="ftpUser">ftp⽤户名</param>48///<param name="ftpPassWord">ftp⽤户名</param>49public FTPHelper(string ftpServerURL, string ftpUser, string ftpPassWord)50 {51this.ftpServerURL = ftpServerURL;52this.ftpUser = ftpUser;53this.ftpPassWord = ftpPassWord;54 }55///<summary>56///通过⽤户名,密码连接到FTP服务器57///</summary>58///<param name="ftpUser">ftp⽤户名,匿名为“”</param>59///<param name="ftpPassWord">ftp登陆密码,匿名为“”</param>60public FTPHelper(string ftpUser, string ftpPassWord)61 {62this.ftpUser = ftpUser;63this.ftpPassWord = ftpPassWord;64 }6566///<summary>67///匿名访问68///</summary>69public FTPHelper(string ftpURL)70 {71this.ftpUser = "";72this.ftpPassWord = "";73 }747576//**************************************************** Start_1 *********************************************************//77///<summary>78///从FTP下载⽂件到本地服务器,⽀持断点下载79///</summary>80///<param name="ftpFilePath">ftp⽂件路径,如"ftp://localhost/test.txt"</param>81///<param name="saveFilePath">保存⽂件的路径,如C:\\test.txt</param>82public void BreakPointDownLoadFile(string ftpFilePath, string saveFilePath)83 {84 System.IO.FileStream fs = null;85 .FtpWebResponse ftpRes = null;86 System.IO.Stream resStrm = null;87try88 {89//下载⽂件的URI90 Uri uri = new Uri(ftpFilePath);91//设定下载⽂件的保存路径92string downFile = saveFilePath;9394//FtpWebRequest的作成95 .FtpWebRequest ftpReq = (.FtpWebRequest)96 .WebRequest.Create(uri);97//设定⽤户名和密码98 ftpReq.Credentials = new workCredential(ftpUser, ftpPassWord);99//MethodにWebRequestMethods.Ftp.DownloadFile("RETR")设定100 ftpReq.Method = .WebRequestMethods.Ftp.DownloadFile;101//要求终了后关闭连接102 ftpReq.KeepAlive = false;103//使⽤ASCII⽅式传送104 eBinary = false;105//设定PASSIVE⽅式⽆效106 ePassive = false;107108//判断是否继续下载109//继续写⼊下载⽂件的FileStream110if (System.IO.File.Exists(downFile))111 {112//继续下载113 ftpReq.ContentOffset = (new System.IO.FileInfo(downFile)).Length;114 fs = new System.IO.FileStream(115 downFile, System.IO.FileMode.Append, System.IO.FileAccess.Write);116 }117else118 {119//⼀般下载120 fs = new System.IO.FileStream(121 downFile, System.IO.FileMode.Create, System.IO.FileAccess.Write);122 }123124//取得FtpWebResponse125 ftpRes = (.FtpWebResponse)ftpReq.GetResponse();126//为了下载⽂件取得Stream127 resStrm = ftpRes.GetResponseStream();128//写⼊下载的数据129byte[] buffer = new byte[1024];130while (true)131 {132int readSize = resStrm.Read(buffer, 0, buffer.Length);133if (readSize == 0)134break;135 fs.Write(buffer, 0, readSize);136 }137 }138catch (Exception ex)139 {140throw new Exception("从ftp服务器下载⽂件出错,⽂件名:" + ftpFilePath + "异常信息:" + ex.ToString()); 141 }142finally143 {144 fs.Close();145 resStrm.Close();146 ftpRes.Close();147 }148 }149150151#region152//从FTP上下载整个⽂件夹,包括⽂件夹下的⽂件和⽂件夹函数列表153154///<summary>155///从ftp下载⽂件到本地服务器156///</summary>157///<param name="ftpFilePath">要下载的ftp⽂件路径,如ftp://192.168.1.104/capture-2.avi</param>158///<param name="saveFilePath">本地保存⽂件的路径,如(@"d:\capture-22.avi"</param>159public void DownLoadFile(string ftpFilePath, string saveFilePath)160 {161 Stream responseStream = null;162 FileStream fileStream = null;163 StreamReader reader = null;164try165 {166// string downloadUrl = "ftp://192.168.1.104/capture-2.avi";167 FtpWebRequest downloadRequest = (FtpWebRequest)WebRequest.Create(ftpFilePath);168 downloadRequest.Method = WebRequestMethods.Ftp.DownloadFile;169 downloadRequest.Credentials = new NetworkCredential(ftpUser, ftpPassWord);170 FtpWebResponse downloadResponse = (FtpWebResponse)downloadRequest.GetResponse();171 responseStream = downloadResponse.GetResponseStream();172173 fileStream = File.Create(saveFilePath);174byte[] buffer = new byte[1024];175int bytesRead;176while (true)177 {178 bytesRead = responseStream.Read(buffer, 0, buffer.Length);179if (bytesRead == 0)180break;181 fileStream.Write(buffer, 0, bytesRead);182 }183 }184catch (Exception ex)185 {186throw new Exception("从ftp服务器下载⽂件出错,⽂件名:" + ftpFilePath + "异常信息:" + ex.ToString()); 187 }188finally189 {190if (reader != null)191 {192 reader.Close();193 }194if (responseStream != null)195 {196 responseStream.Close();197 }198if (fileStream != null)199 {200 fileStream.Close();201 }202 }203 }204205206///<summary>207///列出当前⽬录下的所有⽂件和⽬录208///</summary>209///<param name="ftpDirPath">FTP⽬录</param>210///<returns></returns>211public List<FileStruct> ListCurrentDirFilesAndChildDirs(string ftpDirPath)212 {213 WebResponse webresp = null;214 StreamReader ftpFileListReader = null;215 FtpWebRequest ftpRequest = null;216try217 {218 ftpRequest = (FtpWebRequest)WebRequest.Create(new Uri(ftpDirPath));219 ftpRequest.Method = WebRequestMethods.Ftp.ListDirectoryDetails;220 ftpRequest.Credentials = new NetworkCredential(ftpUser, ftpPassWord);221 webresp = ftpRequest.GetResponse();222 ftpFileListReader = new StreamReader(webresp.GetResponseStream(),Encoding.GetEncoding("UTF-8")); 223 }224catch (Exception ex)225 {226throw new Exception("获取⽂件列表出错,错误信息如下:" + ex.ToString());227 }228string Datastring = ftpFileListReader.ReadToEnd();229return GetListX(Datastring);230231 }232233///<summary>234///列出当前⽬录下的所有⽂件235///</summary>236///<param name="ftpDirPath">FTP⽬录</param>237///<returns></returns>238public List<FileStruct> ListCurrentDirFiles(string ftpDirPath)239 {240 List<FileStruct> listAll = ListCurrentDirFilesAndChildDirs(ftpDirPath);241 List<FileStruct> listFile = new List<FileStruct>();242foreach (FileStruct file in listAll)243 {244if (!file.IsDirectory)245 {246 listFile.Add(file);247 }248 }249return listFile;250 }251252253///<summary>254///列出当前⽬录下的所有⼦⽬录255///</summary>256///<param name="ftpDirath">FRTP⽬录</param>257///<returns>⽬录列表</returns>258public List<FileStruct> ListCurrentDirChildDirs(string ftpDirath)259 {260 List<FileStruct> listAll = ListCurrentDirFilesAndChildDirs(ftpDirath);261 List<FileStruct> listDirectory = new List<FileStruct>();262foreach (FileStruct file in listAll)263 {264if (file.IsDirectory)265 {266 listDirectory.Add(file);267 }268 }269return listDirectory;270 }271272273///<summary>274///获得⽂件和⽬录列表(返回类型为: List<FileStruct> )275///</summary>276///<param name="datastring">FTP返回的列表字符信息</param>277private List<FileStruct> GetListX(string datastring)278 {279 List<FileStruct> myListArray = new List<FileStruct>();280string[] dataRecords = datastring.Split('\n');281 FileListStyle _directoryListStyle = GuessFileListStyle(dataRecords);282foreach (string s in dataRecords)283 {284if (_directoryListStyle != FileListStyle.Unknown && s != "")285 {286 FileStruct f = new FileStruct();287 = "..";288switch (_directoryListStyle)289 {290case FileListStyle.UnixStyle:291 f = ParseFileStructFromUnixStyleRecord(s);292break;293case FileListStyle.WindowsStyle:294 f = ParseFileStructFromWindowsStyleRecord(s);295break;296 }297if (!( == "." || == ".."))298 {299 myListArray.Add(f);300 }301 }302 }303return myListArray;304 }305///<summary>306///从Unix格式中返回⽂件信息307///</summary>308///<param name="Record">⽂件信息</param>309private FileStruct ParseFileStructFromUnixStyleRecord(string Record)310 {311 FileStruct f = new FileStruct();312string processstr = Record.Trim();313 f.Flags = processstr.Substring(0, 10);314 f.IsDirectory = (f.Flags[0] == 'd');315 processstr = (processstr.Substring(11)).Trim();316 cutSubstringFromStringWithTrim(ref processstr, '', 0); //跳过⼀部分317 f.Owner = cutSubstringFromStringWithTrim(ref processstr, '', 0);318 f.Group = cutSubstringFromStringWithTrim(ref processstr, '', 0);319 cutSubstringFromStringWithTrim(ref processstr, '', 0); //跳过⼀部分320string yearOrTime = processstr.Split(new char[] { '' }, StringSplitOptions.RemoveEmptyEntries)[2]; 321if (yearOrTime.IndexOf(":") >= 0) //time322 {323 processstr = processstr.Replace(yearOrTime, DateTime.Now.Year.ToString());324 }325 f.CreateTime = DateTime.Parse(cutSubstringFromStringWithTrim(ref processstr, '', 8));326 = processstr; //最后就是名称327return f;328 }329330///<summary>331///从Windows格式中返回⽂件信息332///</summary>333///<param name="Record">⽂件信息</param>334private FileStruct ParseFileStructFromWindowsStyleRecord(string Record)335 {336 FileStruct f = new FileStruct();337string processstr = Record.Trim();338string dateStr = processstr.Substring(0, 8);339 processstr = (processstr.Substring(8, processstr.Length - 8)).Trim();340string timeStr = processstr.Substring(0, 7);341 processstr = (processstr.Substring(7, processstr.Length - 7)).Trim();342 DateTimeFormatInfo myDTFI = new CultureInfo("en-US", false).DateTimeFormat;343 myDTFI.ShortTimePattern = "t";344 f.CreateTime = DateTime.Parse(dateStr + "" + timeStr, myDTFI);345if (processstr.Substring(0, 5) == "<DIR>")346 {347 f.IsDirectory = true;348 processstr = (processstr.Substring(5, processstr.Length - 5)).Trim();349 }350else351 {352string[] strs = processstr.Split(new char[] { '' }, 2);// StringSplitOptions.RemoveEmptyEntries); // true); 353 processstr = strs[1];354 f.IsDirectory = false;355 }356 = processstr;357return f;358 }359360361///<summary>362///按照⼀定的规则进⾏字符串截取363///</summary>364///<param name="s">截取的字符串</param>365///<param name="c">查找的字符</param>366///<param name="startIndex">查找的位置</param>367private string cutSubstringFromStringWithTrim(ref string s, char c, int startIndex)368 {369int pos1 = s.IndexOf(c, startIndex);370string retString = s.Substring(0, pos1);371 s = (s.Substring(pos1)).Trim();372return retString;373 }374375376///<summary>377///判断⽂件列表的⽅式Window⽅式还是Unix⽅式378///</summary>379///<param name="recordList">⽂件信息列表</param>380private FileListStyle GuessFileListStyle(string[] recordList)381 {382foreach (string s in recordList)383 {384if (s.Length > 10385 && Regex.IsMatch(s.Substring(0, 10), "(-|d)(-|r)(-|w)(-|x)(-|r)(-|w)(-|x)(-|r)(-|w)(-|x)"))386 {387return FileListStyle.UnixStyle;388 }389else if (s.Length > 8390 && Regex.IsMatch(s.Substring(0, 8), "[0-9][0-9]-[0-9][0-9]-[0-9][0-9]"))391 {392return FileListStyle.WindowsStyle;393 }394 }395return FileListStyle.Unknown;396 }397398399///<summary>400///从FTP下载整个⽂件夹401///</summary>402///<param name="ftpDirPath">FTP⽂件夹路径</param>403///<param name="saveDirPath">保存的本地⽂件夹路径</param>404///调⽤实例: DownFtpDir("FTP://192.168.1.113/WangJin", @"C:\QMDownload\SoftMgr");405///当调⽤的时候先判断saveDirPath的⼦⽬录中是否有WangJin⽬录,有则执⾏,没有创建后执⾏406///最终⽂件保存在@"C:\QMDownload\SoftMgr\WangJin"下407public bool DownFtpDir(string ftpDirPath, string saveDirPath)408 {409bool success = true;410try411 {412 List<FileStruct> files = ListCurrentDirFilesAndChildDirs(ftpDirPath);413if (!Directory.Exists(saveDirPath))414 {415 Directory.CreateDirectory(saveDirPath);416 }417foreach (FileStruct f in files)418 {419if (f.IsDirectory) //⽂件夹,递归查询421 DownFtpDir(ftpDirPath + "/" + , saveDirPath + "\\" + );422 }423else//⽂件,直接下载424 {425 DownLoadFile(ftpDirPath + "/" + , saveDirPath + "\\" + );426 }427 }428 }429catch (Exception e)430 {431 MessageBox.Show(e.Message);432 success = false;433 }434return success;435 }436#endregion437438439440///<summary>441///列出当前⽬录下的所有⼦⽬录和⽂件到TreeView控件中442///</summary>443///<param name="ftpDirPath"> FTP服务器⽬录</param>444///<param name="treeview">显⽰到TreeView控件中</param>445///<param name="treenode">TreeView控件的⼦节点</param>446public void ListCurrentDirFilesAndDirToTreeView(string ftpDirPath, TreeView treeview, TreeNode treenode) 447 {448if (ftpDirPath == "")449 {450 ftpDirPath = ftpServerURL;451 }452if (treeview != null)453 {454 treeview.Nodes.Clear();455 treenode = treeview.Nodes.Add(ftpDirPath);456 }457 List<FileStruct> files = ListCurrentDirFilesAndChildDirs(ftpDirPath);458foreach (FileStruct f in files)459 {460if (f.IsDirectory) //如果为⽬录(⽂件夹),递归调⽤461 {462 TreeNode td = treenode.Nodes.Add();463 ListCurrentDirFilesAndDirToTreeView(ftpDirPath + "/" + , null, td);464 }465else//如果为⽂件,直接加⼊到节点中466 {467 treenode.Nodes.Add();468 }469 }470 }471//************************************* End_1 ****************************//472473474475476//************************************ Start_2 ***************************//477///<summary>478///检测⽂件或⽂件⽬录是否存在479///</summary>480///<param name="ftpDirPath">ftp服务器中的⽬录路径</param>481///<param name="ftpDirORFileName">待检测的⽂件或⽂件名</param>482///<returns></returns>483///操作实例: ftpclient.fileOrDirCheckExist("FTP://192.168.1.113/Record/", "")484/// ftpclient.fileOrDirCheckExist("FTP://192.168.1.113/RecordFile/", "333.txt")485public bool fileOrDirCheckExist(string ftpDirPath, string ftpDirORFileName)486 {487bool success = true;488 FtpWebRequest ftpWebRequest = null;489 WebResponse webResponse = null;490 StreamReader reader = null;491try492 {493string url = ftpDirPath + ftpDirORFileName;494 ftpWebRequest = (FtpWebRequest)FtpWebRequest.Create(new Uri(url));495 ftpWebRequest.Credentials = new NetworkCredential(ftpUser, ftpPassWord);496 ftpWebRequest.Method = WebRequestMethods.Ftp.ListDirectory;497 ftpWebRequest.KeepAlive = false;498 webResponse = ftpWebRequest.GetResponse();499 reader = new StreamReader(webResponse.GetResponseStream());500string line = reader.ReadLine();501while (line != null)502 {503if (line == ftpDirORFileName)504 {505break;507 line = reader.ReadLine();508 }509 }510catch (Exception)511 {512 success = false;513 }514finally515 {516if (reader != null)517 {518 reader.Close();519 }520if (webResponse != null)521 {522 webResponse.Close();523 }524 }525return success;526 }527528529///<summary>530///获得⽂件和⽬录列表(返回类型为:FileStruct)531///</summary>532///<param name="datastring">FTP返回的列表字符信息</param>533public FileStruct GetList(string datastring)534 {535 FileStruct f = new FileStruct();536string[] dataRecords = datastring.Split('\n');537 FileListStyle _directoryListStyle = GuessFileListStyle(dataRecords);538if (_directoryListStyle != FileListStyle.Unknown && datastring != "")539 {540541switch (_directoryListStyle)542 {543case FileListStyle.UnixStyle:544 f = ParseFileStructFromUnixStyleRecord(datastring);545break;546case FileListStyle.WindowsStyle:547 f = ParseFileStructFromWindowsStyleRecord(datastring);548break;549 }550 }551return f;552 }553554555///<summary>556///上传557///</summary>558///<param name="localFilePath">本地⽂件名路径</param>559///<param name="ftpDirPath">上传到ftp中⽬录的路径</param>560///<param name="ftpFileName">上传到ftp中⽬录的⽂件名</param>561///<param name="fileLength">限制上传⽂件的⼤⼩(Bytes为单位)</param>562///操作实例: ftpclient.fileUpload(@"E:\bin\Debug\Web\RecordFile\wangjin\wangjin.txt", "FTP://192.168.1.113/Record/","123.txt",0 );563public bool UploadFile(FileInfo localFilePath, string ftpDirPath, string ftpFileName, long fileLength)564 {565bool success = true;566long filesize = 0;567 FtpWebRequest ftpWebRequest = null;568 FileStream localFileStream = null;569 Stream requestStream = null;570if (fileLength > 0)571 {572 filesize = fileLength * 1024 * 1024;573 }574if (localFilePath.Length <= filesize || filesize == 0)575 {576if (fileOrDirCheckExist(ftpDirPath.Substring(0, stIndexOf(@"/") + 1), ftpDirPath.Substring(stIndexOf(@"/") + 1))) 577 {578try579 {580string uri = ftpDirPath + ftpFileName;581 ftpWebRequest = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));582 ftpWebRequest.Credentials = new NetworkCredential(ftpUser, ftpPassWord);583 eBinary = true;584 ftpWebRequest.KeepAlive = false;585 ftpWebRequest.Method = WebRequestMethods.Ftp.UploadFile;586 ftpWebRequest.ContentLength = localFilePath.Length;587int buffLength = 2048; //定义缓存⼤⼩2KB588byte[] buff = new byte[buffLength];589int contentLen;590 localFileStream = localFilePath.OpenRead();591 requestStream = ftpWebRequest.GetRequestStream();592 contentLen = localFileStream.Read(buff, 0, buffLength);593while (contentLen != 0)594 {595 requestStream.Write(buff, 0, contentLen);596 contentLen = localFileStream.Read(buff, 0, buffLength);597 }598 }599catch (Exception)600 {601 success = false;602 }603finally604 {605if (requestStream != null)606 {607 requestStream.Close();608 }609if (localFileStream != null)610 {611 localFileStream.Close();612 }613 }614 }615else616 {617 success = false;618 MessageBox.Show("FTP⽂件路径不存在!");619 }620 }621else622 {623 success = false;624 MessageBox.Show("⽂件⼤⼩超过设置范围!" + "\n" + "⽂件实际⼤⼩为:" + localFilePath.Length + "\n" + "允许上传阈值为:" + (5 * 1024 * 1024).ToString()); 625 }626return success;627 }628629///<summary>630///下载⽂件631///</summary>632///<param name="ftpFilePath">需要下载的⽂件名路径</param>633///<param name="localFilePath">本地保存的⽂件名路径)</param>634///操作实例: ftpclient.fileDownload(@"E:\bin\Debug\Web\RecordFile\wangjin\459.txt", "FTP://192.168.1.113/Record/123.txt");635public bool DownloadFile( string localFilePath, string ftpFilePath)636 {637bool success = true;638 FtpWebRequest ftpWebRequest = null;639 FtpWebResponse ftpWebResponse = null;640 Stream ftpResponseStream = null;641 FileStream outputStream = null;642try643 {644 outputStream = new FileStream(localFilePath, FileMode.Create);645string uri = ftpFilePath;646 ftpWebRequest = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));647 ftpWebRequest.Credentials = new NetworkCredential(ftpUser, ftpPassWord);648 eBinary = true;649 ftpWebRequest.Method = WebRequestMethods.Ftp.DownloadFile;650 ftpWebResponse = (FtpWebResponse)ftpWebRequest.GetResponse();651 ftpResponseStream = ftpWebResponse.GetResponseStream();652long contentLength = ftpWebResponse.ContentLength;653int bufferSize = 2048;654byte[] buffer = new byte[bufferSize];655int readCount;656 readCount = ftpResponseStream.Read(buffer, 0, bufferSize);657while (readCount > 0)658 {659 outputStream.Write(buffer, 0, readCount);660 readCount = ftpResponseStream.Read(buffer, 0, bufferSize);661 }662 }663catch (Exception)664 {665 success = false;666 }667finally668 {669if (outputStream != null)670 {671 outputStream.Close();672 }673if (ftpResponseStream != null)674 {675 ftpResponseStream.Close();676 }677if (ftpWebResponse != null)679 ftpWebResponse.Close();680 }681 }682return success;683 }684685686///<summary>687///重命名688///</summary>689///<param name="ftpDirPath">ftp服务器中的⽬录</param>690///<param name="currentFilename">当前要修改的⽂件名</param>691///<param name="newFilename">修改后的新⽂件名</param>692///操作实例: ftpclientxy.fileRename("FTP://192.168.1.113/RecordFile/", "123.txt", "333.txt");693public bool RenameFile(string ftpDirPath, string currentFileName, string newFileName)694 {695bool success = true;696 FtpWebRequest ftpWebRequest = null;697 FtpWebResponse ftpWebResponse = null;698 Stream ftpResponseStream = null;699if (fileOrDirCheckExist(ftpDirPath.Substring(0, stIndexOf(@"/") + 1), ftpDirPath.Substring(stIndexOf(@"/") + 1))) 700 {701try702 {703string uri = ftpDirPath + currentFileName;704 ftpWebRequest = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));705 ftpWebRequest.Credentials = new NetworkCredential(ftpUser, ftpPassWord);706 eBinary = true;707 ftpWebRequest.Method = WebRequestMethods.Ftp.Rename;708 ftpWebRequest.RenameTo = newFileName;709 ftpWebResponse = (FtpWebResponse)ftpWebRequest.GetResponse();710 ftpResponseStream = ftpWebResponse.GetResponseStream();711 }712catch (Exception)713 {714 success = false;715 }716finally717 {718if (ftpResponseStream != null)719 {720 ftpResponseStream.Close();721 }722if (ftpWebResponse != null)723 {724 ftpWebResponse.Close();725 }726 }727 }728else729 {730 success = false;731 MessageBox.Show("FTP⽂件路径不存在!");732 }733return success;734 }735736///<summary>737///在⽬录下创建⼦⽬录738///</summary>739///<param name="ftpDirPath">ftp服务器中的⽬录</param>740///<param name="ftpFileDir">待创建的⼦⽬录</param>741///<returns></returns>742///操作实例: ftpclient.fileDirMake("FTP://192.168.1.113/RecordFile/", "WangJinFile")743public bool MakeDir(string ftpDirPath, string ftpFileDir)744 {745bool success = true;746 FtpWebRequest ftpWebRequest = null;747 WebResponse webResponse = null;748 StreamReader reader = null;749try750 {751string url = ftpDirPath + ftpFileDir;752 ftpWebRequest = (FtpWebRequest)FtpWebRequest.Create(new Uri(url));753// 指定数据传输类型754 eBinary = true;755 ftpWebRequest.Credentials = new NetworkCredential(ftpUser, ftpPassWord);756 ftpWebRequest.Method = WebRequestMethods.Ftp.MakeDirectory;757 webResponse = ftpWebRequest.GetResponse();758 }759catch (Exception)760 {761 success = false;762 }763finally765if (reader != null)766 {767 reader.Close();768 }769if (webResponse != null)770 {771 webResponse.Close();772 }773 }774return success;775 }776777778///<summary>779///删除⽬录中的⽂件780///</summary>781///<param name="ftpDirPath"></param>782///<param name="ftpFileName"></param>783///<returns></returns>784///操作实例: ftpclient.fileDelete("FTP://192.168.1.113/RecordFile/WangJinFile/", "333.txt")785public bool DeleteFile(string ftpDirPath, string ftpFileName)786 {787bool success = true;788 FtpWebRequest ftpWebRequest = null;789 FtpWebResponse ftpWebResponse = null;790 Stream ftpResponseStream = null;791 StreamReader streamReader = null;792try793 {794string uri = ftpDirPath + ftpFileName;795 ftpWebRequest = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));796 ftpWebRequest.Credentials = new NetworkCredential(ftpUser, ftpPassWord);797 ftpWebRequest.KeepAlive = false;798 ftpWebRequest.Method = WebRequestMethods.Ftp.DeleteFile;799 ftpWebResponse = (FtpWebResponse)ftpWebRequest.GetResponse();800long size = ftpWebResponse.ContentLength;801 ftpResponseStream = ftpWebResponse.GetResponseStream();802 streamReader = new StreamReader(ftpResponseStream);803string result = String.Empty;804 result = streamReader.ReadToEnd();805 }806catch (Exception)807 {808 success = false;809 }810finally811 {812if (streamReader != null)813 {814 streamReader.Close();815 }816if (ftpResponseStream != null)817 {818 ftpResponseStream.Close();819 }820if (ftpWebResponse != null)821 {822 ftpWebResponse.Close();823 }824 }825return success;826 }827828///<summary>829///获取⽬录的⼦⽬录数组830///</summary>831///<param name="ftpDirPath"></param>832///<returns></returns>833///操作实例: string []filedir = ftpclient.GetDeleteFolderArray("FTP://192.168.1.113/WangJinFile/"); 834public string[] GetDirArray(string ftpDirPath)835 {836string[] deleteFolders;837 FtpWebRequest ftpWebRequest = null;838 FtpWebResponse ftpWebResponse = null;839 Stream ftpResponseStream = null;840 StreamReader streamReader = null;841 StringBuilder result = new StringBuilder();842try843 {844 ftpWebRequest = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpDirPath));845 eBinary = true;846 ePassive = false;847 ftpWebRequest.Credentials = new NetworkCredential(ftpUser, ftpPassWord);848 ftpWebRequest.Method = WebRequestMethods.Ftp.ListDirectoryDetails;849 ftpWebResponse = (FtpWebResponse)ftpWebRequest.GetResponse();。

后端实现新文件覆盖旧文件的方法

后端实现新文件覆盖旧文件的方法

后端实现新文件覆盖旧文件的方法在后端开发中,经常会遇到需要将一个新文件覆盖掉旧文件的情况。

这种需求通常出现在用户需要更新文件内容、上传新文件或者修改文件配置等场景中。

本文将介绍一些常见的后端实现新文件覆盖旧文件的方法,帮助开发者更好地应对这类需求。

1. 使用文件流操作一种常见的方法是使用文件流操作,即通过读取新文件的内容,然后将其写入到旧文件中。

这种方法适用于文本文件、图片文件等多种类型的文件。

需要使用后端编程语言提供的文件操作相关的函数或类,打开旧文件和新文件。

然后,可以使用循环逐行读取新文件的内容,并将读取的内容写入到旧文件中。

最后,关闭文件流,完成文件覆盖的操作。

2. 使用文件拷贝另一种常见的方法是使用文件拷贝操作,即直接将新文件复制到旧文件的位置。

这种方法适用于二进制文件、压缩文件等不需要修改文件内容的情况。

需要使用后端编程语言提供的文件操作相关的函数或类,打开旧文件和新文件。

然后,可以使用拷贝函数将新文件复制到旧文件的位置。

最后,关闭文件,完成文件覆盖的操作。

需要注意的是,在使用文件拷贝的方法时,应该使用合适的权限设置,确保旧文件可以被覆盖。

同时,还应该注意处理异常情况,例如,新文件不存在或者旧文件被其他进程占用等情况。

3. 使用版本控制工具如果项目中已经使用了版本控制工具,例如Git,那么可以通过版本控制工具来实现文件覆盖的操作。

这种方法适用于需要跟踪文件修改历史、回滚文件修改等场景。

需要使用版本控制工具将旧文件提交到版本库中。

然后,可以使用版本控制工具提供的命令或API,将新文件覆盖旧文件。

最后,提交修改,完成文件覆盖的操作。

使用版本控制工具的方法具有较好的可追踪性和可回滚性,但需要注意版本冲突的处理和权限控制等问题。

4. 使用文件系统操作一些后端开发框架或库提供了文件系统操作的封装,可以简化文件覆盖操作的实现。

例如,Node.js中的fs模块提供了丰富的文件系统操作函数,可以方便地实现文件的读取、写入和复制等操作。

ftp操作方法整理

ftp操作方法整理

ftp操作⽅法整理1.整理简化了下C#的ftp操作,⽅便使⽤1.⽀持创建多级⽬录2.批量删除3.整个⽬录上传4.整个⽬录删除5.整个⽬录下载2.调⽤⽅法展⽰,var ftp = new FtpHelper("10.136.12.11", "qdx1213123", "123ddddf");//初始化ftp,创建ftp对象ftp.DelAll("test");//删除ftptest⽬录及其⽬录下的所有⽂件ftp.UploadAllFile("F:\\test\\wms.zip");//上传单个⽂件到指定⽬录ftp.UploadAllFile("F:\\test");//将本地test⽬录的所有⽂件上传ftp.DownloadFile("test\\wms.zip", "F:\\test1");//下载单个⽬录ftp.DownloadAllFile("test", "F:\\test1");//批量下载整个⽬录ftp.MakeDir("aaa\\bbb\\ccc\\ddd");//创建多级⽬录3.FtpHelper 代码。

1.异常⽅法委托,通过Lamda委托统⼀处理异常,⽅便改写。

加了个委托⽅便控制异常输出2.ftp的删除需要递归查找所有⽬录存⼊list,然后根据 level倒序排序,从最末级开始遍历删除3.其他的整个⽬录操作都是同上1using System;2using System.Collections.Generic;3using System.Linq;4using ;5using System.IO;67namespace MyStuday8 {9///<summary>10/// ftp帮助类11///</summary>12public class FtpHelper13 {14private string ftpHostIP { get; set; }15private string username { get; set; }16private string password { get; set; }17private string ftpURI { get { return $@"ftp://{ftpHostIP}/"; } }1819///<summary>20///初始化ftp参数21///</summary>22///<param name="ftpHostIP">ftp主机IP</param>23///<param name="username">ftp账户</param>24///<param name="password">ftp密码</param>25public FtpHelper(string ftpHostIP, string username, string password)26 {27this.ftpHostIP = ftpHostIP;ername = username;29this.password = password;30 }3132///<summary>33///异常⽅法委托,通过Lamda委托统⼀处理异常,⽅便改写34///</summary>35///<param name="method">当前执⾏的⽅法</param>36///<param name="action"></param>37///<returns></returns>38private bool MethodInvoke(string method, Action action)39 {40if (action != null)41 {42try43 {44 action();45//Logger.Write2File($@"FtpHelper.{method}:执⾏成功");46 FluentConsole.Magenta.Line($@"FtpHelper({ftpHostIP},{username},{password}).{method}:执⾏成功"); 47return true;48 }49catch (Exception ex)50 {51 FluentConsole.Red.Line($@"FtpHelper({ftpHostIP},{username},{password}).{method}:执⾏失败:\n {ex}"); 52// Logger.Write2File(FtpHelper({ftpHostIP},{username},{password}).{method}:执⾏失败 \r\n{ex}");53return false;54 }55 }57 {58return false;59 }60 }6162///<summary>63///异常⽅法委托,通过Lamda委托统⼀处理异常,⽅便改写64///</summary>65///</summary>66///<typeparam name="T"></typeparam>67///<param name="method"></param>68///<param name="func"></param>69///<returns></returns>70private T MethodInvoke<T>(string method, Func<T> func)71 {72if (func != null)73 {74try75 {76//FluentConsole.Magenta.Line($@"FtpHelper({ftpHostIP},{username},{password}).{method}:执⾏成功");77//Logger.Write2File($@"FtpHelper({ftpHostIP},{username},{password}).{method}:执⾏成功");78return func();79 }80catch (Exception ex)81 {82//FluentConsole.Red.Line($@"FtpHelper({ftpHostIP},{username},{password}).{method}:执⾏失败:").Line(ex); 83// Logger.Write2File($@"FtpHelper({ftpHostIP},{username},{password}).{method}:执⾏失败 \r\n{ex}");84return default(T);85 }86 }87else88 {89return default(T);90 }91 }92private FtpWebRequest GetRequest(string URI)93 {94//根据服务器信息FtpWebRequest创建类的对象95 FtpWebRequest result = (FtpWebRequest)WebRequest.Create(URI);96 result.Credentials = new NetworkCredential(username, password);97 result.KeepAlive = false;98 ePassive = false;99 eBinary = true;100return result;101 }102103///<summary>上传⽂件</summary>104///<param name="filePath">需要上传的⽂件路径</param>105///<param name="dirName">⽬标路径</param>106public bool UploadFile(string filePath, string dirName = "")107 {108 FileInfo fileInfo = new FileInfo(filePath);109if (dirName != "") MakeDir(dirName);//检查⽂件⽬录,不存在就⾃动创建110string uri = bine(ftpURI, dirName, );111return MethodInvoke($@"uploadFile({filePath},{dirName})", () =>112 {113 FtpWebRequest ftp = GetRequest(uri);114 ftp.Method = WebRequestMethods.Ftp.UploadFile;115 ftp.ContentLength = fileInfo.Length;116int buffLength = 2048;117byte[] buff = new byte[buffLength];118int contentLen;119using (FileStream fs = fileInfo.OpenRead())120 {121using (Stream strm = ftp.GetRequestStream())122 {123 contentLen = fs.Read(buff, 0, buffLength);124while (contentLen != 0)125 {126 strm.Write(buff, 0, contentLen);127 contentLen = fs.Read(buff, 0, buffLength);128 }129 strm.Close();130 }131 fs.Close();132 }133 });134 }135136///<summary>137///从⼀个⽬录将其内容复制到另⼀⽬录138///</summary>139///<param name="localDir">源⽬录</param>140///<param name="DirName">⽬标⽬录</param>141public void UploadAllFile(string localDir, string DirName = "")142 {143string localDirName = string.Empty;144int targIndex = stIndexOf("\\");145if (targIndex > -1 && targIndex != (localDir.IndexOf(":\\") + 1))146 localDirName = localDir.Substring(0, targIndex);147 localDirName = localDir.Substring(targIndex + 1);148string newDir = bine(DirName, localDirName);149 MethodInvoke($@"UploadAllFile({localDir},{DirName})", () =>151 MakeDir(newDir);152 DirectoryInfo directoryInfo = new DirectoryInfo(localDir);153 FileInfo[] files = directoryInfo.GetFiles();154//复制所有⽂件155foreach (FileInfo file in files)156 {157 UploadFile(file.FullName, newDir);158 }159//最后复制⽬录160 DirectoryInfo[] directoryInfoArray = directoryInfo.GetDirectories();161foreach (DirectoryInfo dir in directoryInfoArray)162 {163 UploadAllFile(bine(localDir, ), newDir);164 }165 });166 }167168///<summary>169///删除单个⽂件170///</summary>171///<param name="filePath"></param>172public bool DelFile(string filePath)173 {174string uri = bine(ftpURI, filePath);175return MethodInvoke($@"DelFile({filePath})", () =>176 {177 FtpWebRequest ftp = GetRequest(uri);178 ftp.Method = WebRequestMethods.Ftp.DeleteFile;179 FtpWebResponse response = (FtpWebResponse)ftp.GetResponse();180 response.Close();181 });182 }183184///<summary>185///删除最末及空⽬录186///</summary>187///<param name="dirName"></param>188private bool DelDir(string dirName)189 {190string uri = bine(ftpURI, dirName);191return MethodInvoke($@"DelDir({dirName})", () =>192 {193 FtpWebRequest ftp = GetRequest(uri);194 ftp.Method = WebRequestMethods.Ftp.RemoveDirectory;195 FtpWebResponse response = (FtpWebResponse)ftp.GetResponse();196 response.Close();197 });198 }199200///<summary>删除⽬录或者其⽬录下所有的⽂件</summary>201///<param name="dirName">⽬录名称</param>202///<param name="ifDelSub">是否删除⽬录下所有的⽂件</param>203public bool DelAll(string dirName)204 {205var list = GetAllFtpFile(new List<ActFile>(),dirName);206if (list == null) return DelDir(dirName);207if (list.Count==0) return DelDir(dirName);//删除当前⽬录208var newlist = list.OrderByDescending(x => x.level);209foreach (var item in newlist)210 {211 FluentConsole.Yellow.Line($@"level:{item.level},isDir:{item.isDir},path:{item.path}"); 212 }213string uri = bine(ftpURI, dirName);214return MethodInvoke($@"DelAll({dirName})", () =>215 {216foreach (var item in newlist)217 {218if (item.isDir)//判断是⽬录调⽤⽬录的删除⽅法219 DelDir(item.path);220else221 DelFile(item.path);222 }223 DelDir(dirName);//删除当前⽬录224return true;225 });226 }227228///<summary>229///下载单个⽂件230///</summary>231///<param name="ftpFilePath">从ftp要下载的⽂件路径</param>232///<param name="localDir">下载⾄本地路径</param>233///<param name="filename">⽂件名</param>234public bool DownloadFile(string ftpFilePath, string saveDir)235 {236string filename = ftpFilePath.Substring(stIndexOf("\\") + 1);237string tmpname = Guid.NewGuid().ToString();238string uri = bine(ftpURI, ftpFilePath);239return MethodInvoke($@"DownloadFile({ftpFilePath},{saveDir},{filename})", () =>240 {241if (!Directory.Exists(saveDir)) Directory.CreateDirectory(saveDir);242 FtpWebRequest ftp = GetRequest(uri);246using (Stream responseStream = response.GetResponseStream())247 {248using (FileStream fs = new FileStream(bine(saveDir, filename), FileMode.CreateNew))249 {250byte[] buffer = new byte[2048];251int read = 0;252do253 {254 read = responseStream.Read(buffer, 0, buffer.Length);255 fs.Write(buffer, 0, read);256 } while (!(read == 0));257 responseStream.Close();258 fs.Flush();259 fs.Close();260 }261 responseStream.Close();262 }263 response.Close();264 }265 });266 }267268///<summary>269///从FTP下载整个⽂件夹270///</summary>271///<param name="dirName">FTP⽂件夹路径</param>272///<param name="saveDir">保存的本地⽂件夹路径</param>273public void DownloadAllFile(string dirName, string saveDir)274 {275 MethodInvoke($@"DownloadAllFile({dirName},{saveDir})", () =>276 {277 List<ActFile> files = GetFtpFile(dirName);278if (!Directory.Exists(saveDir))279 {280 Directory.CreateDirectory(saveDir);281 }282foreach (var f in files)283 {284if (f.isDir) //⽂件夹,递归查询285 {286 DownloadAllFile(bine(dirName,), bine(saveDir ,));287 }288else//⽂件,直接下载289 {290 DownloadFile(bine(dirName,), saveDir);291 }292 }293 });294 }295296///<summary>297///获取当前⽬录下的⽬录及⽂件298///</summary>299/// param name="ftpfileList"></param>300///<param name="dirName"></param>301///<returns></returns>302public List<ActFile> GetFtpFile(string dirName,int ilevel = 0)303 {304var ftpfileList = new List<ActFile>();305string uri = bine(ftpURI, dirName);306return MethodInvoke($@"GetFtpFile({dirName})", () =>307 {308var a = new List<List<string>>();309 FtpWebRequest ftp = GetRequest(uri);310 ftp.Method = WebRequestMethods.Ftp.ListDirectoryDetails;311 Stream stream = ftp.GetResponse().GetResponseStream();312using (StreamReader sr = new StreamReader(stream))313 {314string line = sr.ReadLine();315while (!string.IsNullOrEmpty(line))316 {317 ftpfileList.Add(new ActFile { isDir = line.IndexOf("<DIR>") > -1, name = line.Substring(39).Trim(), path = bine(dirName, line.Substring(39).Trim()), level= ilevel }); 318 line = sr.ReadLine();319 }320 sr.Close();321 }322return ftpfileList;323 });324325326 }327328///<summary>329///获取FTP⽬录下的所有⽬录及⽂件包括其⼦⽬录和⼦⽂件330///</summary>331/// param name="result"></param>332///<param name="dirName"></param>333///<returns></returns>334public List<ActFile> GetAllFtpFile(List<ActFile> result,string dirName, int level = 0)335 {336var ftpfileList = new List<ActFile>();340 ftpfileList = GetFtpFile(dirName, level);341 result.AddRange(ftpfileList);342var newlist = ftpfileList.Where(x => x.isDir).ToList();343foreach (var item in newlist)344 {345 GetAllFtpFile(result,item.path, level+1);346 }347return result;348 });349350 }351352///<summary>353///检查⽬录是否存在354///</summary>355///<param name="dirName"></param>356///<param name="currentDir"></param>357///<returns></returns>358public bool CheckDir(string dirName, string currentDir = "")359 {360string uri = bine(ftpURI, currentDir);361return MethodInvoke($@"CheckDir({dirName}{currentDir})", () =>362 {363 FtpWebRequest ftp = GetRequest(uri);364 eBinary = true;365 ftp.Method = WebRequestMethods.Ftp.ListDirectoryDetails;366 Stream stream = ftp.GetResponse().GetResponseStream();367using (StreamReader sr = new StreamReader(stream))368 {369string line = sr.ReadLine();370while (!string.IsNullOrEmpty(line))371 {372if (line.IndexOf("<DIR>") > -1)373 {374if (line.Substring(39).Trim() == dirName)375return true;376 }377 line = sr.ReadLine();378 }379 sr.Close();380 }381 stream.Close();382return false;383 });384385 }386387///</summary>388///在ftp服务器上创建指定⽬录,⽗⽬录不存在则创建389///</summary>390///<param name="dirName">创建的⽬录名称</param>391public bool MakeDir(string dirName)392 {393var dirs = dirName.Split('\\').ToList();//针对多级⽬录分割394string currentDir = string.Empty;395return MethodInvoke($@"MakeDir({dirName})", () =>396 {397foreach (var dir in dirs)398 {399if (!CheckDir(dir, currentDir))//检查⽬录不存在则创建400 {401 currentDir = bine(currentDir, dir);402string uri = bine(ftpURI, currentDir);403 FtpWebRequest ftp = GetRequest(uri);404 ftp.Method = WebRequestMethods.Ftp.MakeDirectory;405 FtpWebResponse response = (FtpWebResponse)ftp.GetResponse();406 response.Close();407 }408else409 {410 currentDir = bine(currentDir, dir);411 }412 }413414 });415416 }417418///<summary>⽂件重命名</summary>419///<param name="currentFilename">当前名称</param>420///<param name="newFilename">重命名名称</param>421///<param name="currentFilename">所在的⽬录</param>422public bool Rename(string currentFilename, string newFilename, string dirName = "") 423 {424string uri = bine(ftpURI, dirName, currentFilename);425return MethodInvoke($@"Rename({currentFilename},{newFilename},{dirName})", () => 426 {427 FtpWebRequest ftp = GetRequest(uri);428 ftp.Method = WebRequestMethods.Ftp.Rename;429 ftp.RenameTo = newFilename;430 FtpWebResponse response = (FtpWebResponse)ftp.GetResponse();434 }435436public class ActFile437 {438public int level { get; set; } = 0; 439public bool isDir { get; set; }440public string name { get; set; } 441public string path { get; set; } = ""; 442 }443 }。

FTP命令基本使用方法

FTP命令基本使用方法

FTP命令基本使用方法1.连接到FTP服务器:2.显示当前目录:命令:pwd这将显示你当前所在的目录。

3.切换目录:命令:cd directory将directory替换为你要切换到的目录的名称。

4.列出目录内容:命令:ls这将列出当前目录的文件和子目录。

命令:get filename6.上传文件:命令:put filename将filename替换为你要上传的文件名。

7.创建目录:命令:mkdir directory将directory替换为你要创建的目录的名称。

8.删除目录:命令:rmdir directory将directory替换为你要删除的目录的名称。

注意,目录必须为空才能被删除。

9.删除文件:命令:delete filename将filename替换为你要删除的文件名。

10.重命名文件:命令:rename oldfilename newfilename将oldfilename替换为要重命名的文件名,newfilename替换为新的文件名。

11.退出FTP会话:命令:quit这将关闭FTP连接并退出FTP会话。

12.传输模式:默认情况下,FTP使用二进制传输模式来传输文件,但有时你可能需要切换到文本模式,尤其是在传输文本文件时。

命令:ascii切换到文本传输模式。

命令:binary切换回二进制传输模式。

13.被动模式:如果你的FTP服务器在防火墙后面,你可能需要切换到被动模式来确保数据传输的正常进行。

命令:passive切换到被动模式。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

注意:mput上传可以带目录,put只上传文件,但put上传只能上传登录ftp 前停留的目录。

mput上传的文件路径,用户必须有访问权限。

否则无法上传。

#!/bin/sh
echo>/home/oracle/ftp/Thu_ftp
rq=$(date +%Y%m%d)
find /u01/backup/data/ora_rman_backup/ticket1/Thu/log/ | grep $rq>
/home/oracle/ftp/Thu_ftp
echo "open 192.168.248.106" >>/home/oracle/ftp/ftpcmd
echo "user ftp Sports-BsT_BeiJing ">>/home/oracle/ftp/ftpcmd
awk '{print "prompt mput ",$0;}' ftpfile>>/home/oracle/ftp/ftpcmd echo "quit">>/home/oracle/ftp/ftpcmd
echo>/home/oracle/ftp/ftp.out
ftp -ivn<ftpcmd>/home/oracle/ftp/ftp.out
egrep -i "ABORT|NOT|DENIED|ERROR|FAIL|A DIRECTORY|NO SUCH"
ftp.out>/dev/null
if [ $? -ne 0 ];then
exit
fi
exit
还有一种方法 justkk说的也要先把上传的文件找出来写到ftpfile里
#!/bin/ksh
(
echo "user abcabc"
echo "bin"
cat ftpfile|xargs -n1 echo put
) | ftp -inv ftp-ip-address
这个还比较麻烦,可以把ftp的输出信息定向到一个文件中,检查文件中是否有错误信息
ftp -ivn<ftpcmd>ftp.out
egrep -i "ABORT|NOT|DENIED|ERROR|FAIL|A DIRECTORY|NO SUCH"
ftp.out>/dev/null
if [ $? -ne 0 ];then
exit
fi
简化了一下,应该也更精确,通过FTP协议的响应码判断.
ftp -ivn<ftpcmd>ftp.out
grep "^[45]" ftp.out>/dev/null
if [ $? -ne 0 ];then
exit
fi
有个ftpfile 这里面就是上传的文件
上传完了这样删除
cat ftpfile | xargsrm -rf
"日期不是今天的文件"可以通过find命令查找
find . -mtime +1。

相关文档
最新文档