File Transfer with SCP
SCP (Secure Copy Protocol) allows you to securely transfer files between your local system and a remote SSH server. NullOpsDevs.LibSsh provides simple methods for both uploading and downloading files using the SCP protocol.
Downloading Files
To download a file from the remote server to your local system:
Download with Custom Buffer Size
You can specify a custom buffer size for better performance with large files:
Async Download
For non-blocking file downloads:
Uploading Files
To upload a file from your local system to the remote server:
Upload with Unix Permissions
You can specify Unix file permissions when uploading:
Common Unix permission modes:
Permissions | Octal | Decimal | Description |
|---|---|---|---|
| 0644 | 420 | Default file (owner read/write, others read) |
| 0755 | 493 | Executable file (owner full, others read/execute) |
| 0600 | 384 | Private file (owner read/write only) |
| 0777 | 511 | Full permissions (not recommended) |
Upload with Custom Buffer Size
Async Upload
For non-blocking file uploads:
Complete Example
Here's a complete example showing both upload and download:
Important Notes
Stream Management:
The
ReadFile()andWriteFile()methods do NOT close the streamsYou are responsible for disposing streams (use
usingstatements)
Stream Requirements:
Upload streams must be readable and seekable
Download streams must be writable
File size is determined from stream length for uploads
Return Value:
Both methods return
trueif the entire file was transferred successfullyReturns
falseif the transfer was incomplete
Session State:
The session must be in
LoggedInstate (authenticated) before transferring files
File Paths:
Use absolute paths on the remote server
Path interpretation depends on the user's home directory and permissions
Error Handling
Always handle potential errors when transferring files:
Performance Tips
Buffer Size:
Default buffer size is 32KB
For large files, consider 64KB or 128KB buffers
Don't use excessively large buffers (>1MB) - diminishing returns
Network Conditions:
Larger buffers help on high-latency networks
Smaller buffers may be better on unstable connections
File Size:
SCP is efficient for single file transfers
For multiple small files, consider archiving them first (tar/zip)
Async Methods:
Use async methods to avoid blocking the UI thread
Helpful for responsive applications during large transfers
See Also
SshSession.ReadFile()(SshSession.cs:555) - Download files via SCPSshSession.WriteFile()(SshSession.cs:636) - Upload files via SCPSshSession.ReadFileAsync()(SshSession.cs:614) - Async downloadSshSession.WriteFileAsync()(SshSession.cs:707) - Async uploadAuthentication - Authenticate before file transfers
Session Timeouts - Set timeouts for large file transfers
Session Lifecycle - Understanding session states
Error Handling - Handle file transfer errors