This is an old revision of the document!
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 {0} exists" -f $remotePath) }
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 need to use Session.ListDirectory and query returned list of files.
Advertisement
Using WinSCP Scripting
You can use a stat command in 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 ^ "option batch abort" ^ "open mysession" ^ "stat %REMOTE_PATH%" ^ "exit" if %ERRORLEVEL% neq 0 goto error echo File %REMOTE_PATH% exists rem Do something exit 0 :error echo Error or file %REMOTE_PATH% not exists exit 1
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 ^ "option batch abort" ^ "open mysession" ^ "option failonnomatch on" ^ "ls %REMOTE_PATH%" ^ "exit"
Advertisement
Local file existence
- In PowerShell, use
Test-Pathcmdlet. See example. - In a batch file, use
if existcommand. See example. - In .NET, use
File.Existsmethod. See C# and VB.NET example. - In WSH, use
Scripting.FileSystemObject.FileExistsmethod. See JScript and VBScript example.