我需要使用FtpWebRequest
将一个文件放到FTP目录中。在上传之前,我首先想知道这个文件是否存在。
我应该使用什么方法或属性来检查该文件是否存在?
发布于 2008-12-07 23:40:39
var request = (FtpWebRequest)WebRequest.Create
("ftp://ftp.domain.com/doesntexist.txt");
request.Credentials = new NetworkCredential("user", "pass");
request.Method = WebRequestMethods.Ftp.GetFileSize;
try
{
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
}
catch (WebException ex)
{
FtpWebResponse response = (FtpWebResponse)ex.Response;
if (response.StatusCode ==
FtpStatusCode.ActionNotTakenFileUnavailable)
{
//Does not exist
}
}
一般来说,在代码中为功能使用异常是一个糟糕的想法,但在这种情况下,我相信这是实用主义的胜利。目录上的呼叫列表可能比以这种方式使用异常的效率低得多。
如果不是,请注意这不是一个好的练习!
编辑:“这对我很有效!”
这似乎适用于大多数ftp服务器,但不是所有服务器。一些服务器需要发送"TYPE I“才能使用SIZE命令。人们会认为这个问题应该像下面这样解决:
request.UseBinary = true;
不幸的是,这是一个设计上的限制(大错误!)除非FtpWebRequest正在下载或上传文件,否则它不会发送"TYPE“。请参阅讨论和微软响应here。
我建议使用下面的WebRequestMethod,它适用于我测试的所有服务器,即使是那些不会返回文件大小的服务器。
WebRequestMethods.Ftp.GetDateTimestamp
发布于 2015-09-16 23:39:42
因为
request.Method = WebRequestMethods.Ftp.GetFileSize
在某些情况下可能会失败(550:在ASCII模式下不允许大小),您可以只检查时间戳。
reqFTP.Credentials = new NetworkCredential(inf.LogOn, inf.Password);
reqFTP.UseBinary = true;
reqFTP.Method = WebRequestMethods.Ftp.GetDateTimestamp;
发布于 2021-08-11 07:57:32
你可以使用WebRequestMethods.Ftp.ListDirectory
来检查文件是否存在,不需要讨厌的try catch机制。
private static bool ExistFile(string remoteAddress)
{
int pos = remoteAddress.LastIndexOf('/');
string dirPath = remoteAddress.Substring(0, pos); // skip the filename only get the directory
NetworkCredential credentials = new NetworkCredential(FtpUser, FtpPass);
FtpWebRequest listRequest = (FtpWebRequest)WebRequest.Create(dirPath);
listRequest.Method = WebRequestMethods.Ftp.ListDirectory;
listRequest.Credentials = credentials;
using (FtpWebResponse listResponse = (FtpWebResponse)listRequest.GetResponse())
using (Stream listStream = listResponse.GetResponseStream())
using (StreamReader listReader = new StreamReader(listStream))
{
string fileToTest = Path.GetFileName(remoteAddress);
while (!listReader.EndOfStream)
{
string fileName = listReader.ReadLine();
fileName = Path.GetFileName(fileName);
if (fileToTest == fileName)
{
return true;
}
}
}
return false;
}
static void Main(string[] args)
{
bool existFile = ExistFile("ftp://123.456.789.12/test/config.json");
}
https://stackoverflow.com/questions/347897
复制相似问题