[英]How to check if file exists in remote folder via FTP?
我想检查远程文件夹的内容,并确定该文件夹中是否存在特定文件(我仅按文件名进行检查,所以chill:D)
示例:我想检查/testftp
文件夹中/testftp
包含textfile.txt
文件。
我这样做是为了获取文件夹内容:
FtpWebRequest request = (FtpWebRequest)WebRequest.Create("myftpaddress");
request.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
request.Credentials = new NetworkCredential("uid", "pass");
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
Stream responseStream = response.GetResponseStream();
StreamReader reader = new StreamReader(responseStream);
Console.WriteLine(reader.ReadToEnd());
Console.WriteLine("Directory List Complete, status {0}", response.StatusDescription);
reader.Close();
response.Close();
它写在控制台中:
-rw-r--r-- 1 6668 userftp 91137 jul 16 23:20 file1.txt
-rw-r--r-- 1 468 userftp 137 jul 16 18:40 file2.swf
并将完整的流响应写入控制台,如何仅获取文件名? 有更容易的方法吗?
尝试下载文件会更容易。 如果获取到StatusCode指示该文件不存在,则说明该文件不存在。
可能比过滤ListDirectoryDetails
的结果要ListDirectoryDetails
。
更新
为了澄清,您需要做的是:
FtpWebResponse response = (FtpWebResponse) request.GetResponse();
bool fileExists = (response.StatusCode != BAD_COMMAND);
我认为BAD_COMMAND是FtpStatusCode .CantOpenData,但我不确定。 这很容易测试。
string listing = reader.ReadToEnd();
// find all occurrences of the fileName and make sure
// it is bounded by white space or string boundary.
int startIndex = 0;
bool exists = false;
while (true)
{
int index = listing.IndexOf(fileName, startIndex);
if (index == -1) break;
int leadingIndex = index - 1;
int trailingIndex = index + fileName.Length;
if ((leadingIndex == -1 || Char.IsWhiteSpace(listing[leadingIndex]) &&
(trailingIndex == list.Length || Char.IsWhiteSpace(listing[trailingIndex]))
{
exists = true;
break;
}
startIndex = trailingIndex;
}
正则表达式版本:
string pattern = string.Format("(^|\\s){0}(\\s|$)", Regex.Escape(fileName));
Regex regex = new Regex(pattern);
string listing = reader.ReadToEnd();
bool exists = regex.IsMatch(listing);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.