我想检查远程文件夹的内容,并确定该文件夹中是否存在特定文件(我只检查文件名,所以冷静:D)
示例:我想检查文件夹/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
它将完整的流响应写入控制台,如何只获取文件名?有更简单的方法吗?
答案 0 :(得分:1)
尝试下载文件会更容易。如果你得到StatusCode表明文件不存在,你知道它不在那里。
可能比过滤ListDirectoryDetails
的结果要少。
更新
澄清一下,您需要做的就是:
FtpWebResponse response = (FtpWebResponse) request.GetResponse();
bool fileExists = (response.StatusCode != BAD_COMMAND);
我认为BAD_COMMAND将是FtpStatusCode。CantOpenData但我不确定。这很容易测试。
答案 1 :(得分:0)
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);