我有一个关于使用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)
{
}
}
Run Code Online (Sandbox Code Playgroud)
我把它扔在一起并不是特别优雅,但我想这几乎是你所需要的?
你只是想继续尝试你的请求,直到你得到一个"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;
}
}
Run Code Online (Sandbox Code Playgroud)
编辑:已更新,因此这适用于任何类型的Web请求,并且稍微有点苗条.
| 归档时间: |
|
| 查看次数: |
14398 次 |
| 最近记录: |