Illep
Illep

Reputation: 16849

Check if file exist on SFTP remote server

The following code will download the file named file.txt from the SFTP remote server to the local machine.

sftp.Get("/usr/mine/file.txt" , "C:/Folder/");

What I want to do is check if the file file.txt exist on the remote server or not. How can I do this check?

I am using SharpSSH

Upvotes: 4

Views: 23309

Answers (3)

Wigle
Wigle

Reputation: 106

This should do the trick.

using (var sftp = new SftpClient(host, username, password))
{
    try
    {

        sftp.Connect();
        MessageBox.Show(sftp.Exists(remoteDirectory).ToString());
    }
    catch (Exception Sftpex)
    {
        MessageBox.Show(Sftpex.ToString());
    }
}

Upvotes: 4

George Vaisey
George Vaisey

Reputation: 149

I'm doing this by using .GetFileList and reading the values into an ArrayList and then looping thru each value, adding the filename to a list box. I then check my input file against the list box to see if it exists. Sample code below to add the .GetFileList values into an ArrayList and then into a list box.

BTW - this is VB.NET :)

Dim InputFileList As ArrayList = oSftp.GetFileList(frmOptions.tbFTPInboundFolder.Text)
 For Each f In InputFileList
                If f.ToString() <> "." AndAlso f.ToString <> ".." Then
                    frmMain.lbFTPInputDirectory.Items.Add(f)
                End If
            Next

Upvotes: 0

Bryan Crosby
Bryan Crosby

Reputation: 6554

You could consider just taking the small hit and attempting to download the file. If it doesn't exist, an exception should be thrown and you can just catch it and move on. Checking for a file's existence is a volatile situation so in the majority of cases it's best to try and perform your action.

Upvotes: 3

Related Questions