2012-07-16 166 views
1

我要检查远程文件夹的内容,并确定特定文件这个文件夹中是否存在(我只检查按文件名,所以寒意:d)如何通过FTP检查远程文件夹中是否存在文件?

例子:我要检查,如果该文件夹中/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 

,并将其写入全码流响应到控制台,如何获得唯一的文件名?有更容易的方法吗?

+1

你的问题是http://stackoverflow.com/questions/347897/how-to-check-if-file-exists-on-ftp-的副本before-ftpwebrequest – HatSoft 2012-07-16 22:36:08

回答

1

只是尝试下载文件会更容易。如果你得到StatusCode表示文件不存在,你就知道它不在那里。

可能比筛选ListDirectoryDetails的结果要少一些工作。

更新

为了澄清,所有你需要做的是这样的:

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

我觉得BAD_COMMAND会FtpStatusCode .CantOpenData,但我不知道。这很容易测试。

+0

如果该文件存在,则会导致下载它的成本。 – 2012-07-16 22:42:51

+0

只有当您调用'reader.ReadToEnd()'时,才需要确定资源是否存在。 – 2012-07-16 22:55:32

+0

我不明白怎么不调用'reader.ReaderToEnd()'防止FTP服务器发送文件的内容?当然,关闭响应流可能会在收到所有字节之前关闭连接。 – 2012-07-16 23:21:25

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); 
+1

如果列表包含文件'textfile.txt.old'会怎么样?这将错误地与您的代码相匹配。 – 2012-07-16 22:39:12

+0

@EricJ。同意。 :/ – 2012-07-16 22:39:59

+0

您可以使用RegEx与周围的空格/换行符进行匹配,但只需通过尝试下载文件来测试文件的存在就可以减少工作量:-) – 2012-07-16 22:40:54

相关问题