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; 

它现在似乎工作。