Checking file existence

Remote file existence

Using WinSCP .NET Assembly

Use method Session.FileExists from WinSCP .NET assembly.

The following example uses a PowerShell script. If you have another preferred language, you can easily translate it.

$remotePath = "/home/user/test.txt"
 
if ($session.FileExists($remotePath))
{
    Write-Host "File $remotePath exists"
}

See complete PowerShell example for Session.FileExists.

If you are not looking for a specific file, but for any file matching a mask (e.g. *.txt), you can use the Session.EnumerateRemoteFiles. For a complex example, that uses this technique, see Downloading files from FTP/SFTP server only after “done” file is created.

Advertisement

Using WinSCP Scripting

You can use a stat command in the (default) option batch abort mode to query file attributes. If the file does not exist, the stat command fails and so does the script. Then, test WinSCP exit code to determine, if the file exists or not.

@echo off
 
set REMOTE_PATH=/home/user/test.txt
winscp.com /command ^
    "open mysession" ^
    "stat %REMOTE_PATH%" ^
    "exit"
 
if %ERRORLEVEL% neq 0 goto error
 
echo File %REMOTE_PATH% exists
rem Do something
exit /b 0
 
:error
echo Error or file %REMOTE_PATH% not exists
exit /b 1

If the further processing involves WinSCP commands, you can add the commands directly to the main WinSCP script, just after the stat command. For an example, see Downloading files from FTP/SFTP server only after “done” file is created.

To check for existence of any file matching a mask, instead of a specific file, enable option failonnomatch on mode and use ls mask command, instead of stat name command:

set REMOTE_PATH=/home/user/*.txt
winscp.com /command ^
    "open mysession" ^
    "option failonnomatch on" ^
    "ls %REMOTE_PATH%" ^
    "exit"

Advertisement

Local file existence

Further Reading

Last modified: by martin