How to check if file exists in remote folder via FTP?

I want to check remote folder's content, and determine if the particular file exists in this folder (I'm checking only by filename, so chill :D)

Example: I want to check if in the folder /testftp contains a textfile.txt file.

I'm doing this to get folder content:

      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("Directory List Complete, status {0}", response.StatusDescription);


it writes in console:

-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

and it writes full stream response into console, how to get only file names? Is there an easier way?


It would be easier to just try and download the file. If you get StatusCode indicating that the file does not exist, you know it was not there.

Probably less work than filtering the result of ListDirectoryDetails.


To clarify, all you need to do is this:

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

I think BAD_COMMAND would be FtpStatusCode.CantOpenData but I'm not sure. That's easily tested.

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;

    startIndex = trailingIndex;

Regex version:

string pattern = string.Format("(^|\\s){0}(\\s|$)", Regex.Escape(fileName));
Regex regex = new Regex(pattern);

string listing = reader.ReadToEnd();
bool exists = regex.IsMatch(listing);

Need Your Help

How to add a time interval to an NSDate?

objective-c cocoa cocoa-touch nsdate date-arithmetic

I have an NSDate and a duration. I need to get the time after the duration

Object reference not set to an instance of an object.postmethod POST filename file while uploading image but **works correctly with Android code**

ios objective-c xcode nsurlconnection

I am getting Object reference not set to an instance of an object.postmethod POST filename file in response when I send a request (from objective c) to server.