1

我想检查远程文件夹的内容,并确定该文件夹中是否存在特定文件(我只检查文件名,所以冷静: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

并将完整的流响应写入控制台,如何仅获取文件名?有没有更简单的方法?

4

2 回答 2

1

尝试下载文件会更容易。如果您得到指示该文件不存在的StatusCode ,您就知道它不存在。

可能比过滤ListDirectoryDetails.

更新

为了澄清,您需要做的就是:

FtpWebResponse response = (FtpWebResponse) request.GetResponse();
bool fileExists = (response.StatusCode != BAD_COMMAND);

我认为 BAD_COMMAND 将是FtpStatusCode .CantOpenData 但我不确定。这很容易测试。

于 2012-07-16T22:32:58.723 回答
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);
于 2012-07-16T22:38:23.667 回答