FTP上传时检查文件是否存在,是否在C#中重命名
我有一个关于使用C#上传到FTP的问题。
我想要做的是,如果文件存在,那么我想添加像文件名后面的复制或1,所以它不会替换文件。 有任何想法吗?
var request = (FtpWebRequest)WebRequest.Create(""+destination+file); request.Credentials = new NetworkCredential("", ""); request.Method = WebRequestMethods.Ftp.GetFileSize; try { FtpWebResponse response = (FtpWebResponse)request.GetResponse(); } catch (WebException ex) { FtpWebResponse response = (FtpWebResponse)ex.Response; if (response.StatusCode == FtpStatusCode.ActionNotTakenFileUnavailable) { } }
我把它扔在一起并不是特别优雅,但我想这几乎是你需要的东西?
你只是想继续尝试你的请求,直到你得到一个“ActionNotTakenFileUnavailable”,所以你知道你的文件名是好的,然后只需上传它。
string destination = "ftp://something.com/"; string file = "test.jpg"; string extention = Path.GetExtension(file); string fileName = file.Remove(file.Length - extention.Length); string fileNameCopy = fileName; int attempt = 1; while (!CheckFileExists(GetRequest(destination + "//" + fileNameCopy + extention))) { fileNameCopy = fileName + " (" + attempt.ToString() + ")"; attempt++; } // do your upload, we've got a name that's OK } private static FtpWebRequest GetRequest(string uriString) { var request = (FtpWebRequest)WebRequest.Create(uriString); request.Credentials = new NetworkCredential("", ""); request.Method = WebRequestMethods.Ftp.GetFileSize; return request; } private static bool checkFileExists(WebRequest request) { try { request.GetResponse(); return true; } catch { return false; } }
编辑:已更新,因此这适用于任何类型的Web请求,并且稍微有点苗条。
由于FTP控制协议本质上很慢(发送 – 接收),我建议先上传目录内容并在上传文件之前检查它。 请注意,dir可以返回两个不同的标准:dos和unix
或者,您可以使用MDTM file
命令检查文件是否已存在(用于检索文件的时间戳)。
没有捷径。 您需要dir
目标目录,然后使用#
来确定要使用的名称。
我正在做类似的事情。 我的问题是:
request.Method = WebRequestMethods.Ftp.GetFileSize;
真的没有用。 有时它会有例外,但有时则没有。 并为同一个文件! 不知道为什么。
我改变它,因为Tedd说(谢谢,顺便说一句)
request.Method = WebRequestMethods.Ftp.GetDateTimestamp;
它现在似乎工作。
上述就是C#学习教程:FTP上传时检查文件是否存在,是否在C#中重命名分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/cdevelopment/1020848.html