C# FTP在上传文件时检查文件是否存在,是否在C中重命名#
我有一个关于用C#上传到FTP的问题 我想做的是,如果文件存在,那么我想在文件名后添加Copy或1,这样它就不会替换文件。有什么想法吗C# FTP在上传文件时检查文件是否存在,是否在C中重命名#,c#,.net,ftp,C#,.net,Ftp,我有一个关于用C#上传到FTP的问题 我想做的是,如果文件存在,那么我想在文件名后添加Copy或1,这样它就不会替换文件。有什么想法吗 var request = (FtpWebRequest)WebRequest.Create(""+destination+file); request.Credentials = new NetworkCredential("", ""); request.Method = WebRequestMethods.Ftp.GetFileSize; try {
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)
{
}
}
没有捷径可走。您需要
dir
目标目录,然后使用#
来确定要使用的名称。它不是特别优雅,因为我刚刚把它组合在一起,但我想这正是您需要的
你只想继续尝试你的请求,直到你得到一个“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
或者,您可以使用
file
命令检查文件是否已经存在(用于检索文件的时间戳)。我正在处理类似的问题。我的问题是:
request.Method = WebRequestMethods.Ftp.GetFileSize;
那真的不管用。有时会有例外,有时不会。同一个文件!不知道为什么
我把Tedd说的(谢谢你,顺便说一句)改为
而且现在似乎起作用了。你在哪一部分有问题?看起来您已经准备好了大部分代码。如果您有新问题,请单击按钮询问。如果这个问题有助于提供上下文,请包含一个指向该问题的链接。我没有任何问题。我只是指出,他编写的代码与我使用的代码相同,但对我来说,由于“GetFileSize”的原因,它并没有真正起作用。我通过检查“文件的时间戳”解决了这个问题,现在它似乎可以工作了。我写在这里是因为我从Tedd那里得到了这个想法,我想也许其他人可以从中受益。英雄联盟
request.Method = WebRequestMethods.Ftp.GetDateTimestamp;