More .NET libraries
-
Rebex FTP
.NET FTP client
-
Rebex SSH Shell
.NET SSH Shell
-
Rebex Total Pack
All Rebex .NET libraries together
Back to feature list...
Directory operations
On this page:
- Working with current directory
- Listing directory content
- Listing directory content - recursively
- Listing directory content - on the fly
- Getting raw directory listing
- Finding files
- Creating a directory
- Deleting a directory
- Deleting directories recursively
- Renaming/moving a directory
- Checking directory existence
- Sorting directory content
- LINQ support - IEnumerable<T> collection
Working with current directory
To get current directory, use GetCurrentDirectory
method. To change it, use ChangeDirectory
method.
// set current directory
sftp.ChangeDirectory("/MyData");
// display the current directory to the user
string currentDir = sftp.GetCurrentDirectory();
Console.WriteLine("Current directory changed to: {0}", currentDir);
' set current directory
sftp.ChangeDirectory("/MyData")
' display the current directory to the user
Dim currentDir As String = sftp.GetCurrentDirectory()
Console.WriteLine("Current directory changed to: {0}", currentDir)
The SFTP protocol itself doesn't have a concept of current directory. However, Rebex SFTP emulates it, making it possible to change the current directories and use both absolute and relative paths.
Listing directory content
To retrieve listings of directory content, three methods are available:
GetList
- returns collection ofSftpItem
objectsGetNameList
- returns aString
array of item namesGetRawList
- returns aString
array of item information in Unix-like format (see more)
All these methods accept an optional argument which represents a path and/or a mask (wildcard pattern).
// get items within the current directory
SftpItemCollection currentItems = sftp.GetList();
// get names of items within "/MyData
string[] dataItems = sftp.GetNameList("/MyData");
// get unix-like listing of all ".txt" files in "/MyData"
string[] dataTextFiles = sftp.GetRawList("/MyData/*.txt");
' get items within the current directory
Dim currentItems As SftpItemCollection = sftp.GetList()
' get names of items within "/MyData
Dim dataItems As String() = sftp.GetNameList("/MyData")
' get unix-like listing of all ".txt" files in "/MyData"
Dim dataTextFiles As String() = sftp.GetRawList("/MyData/*.txt")
GetItems
method.
Listing directory content - recursively
To retrieve a listing of directory content including items in subdirectories,
or to use more complex filtering criteria, use GetItems
method.
TraversalMode
and Rebex.IO.FileSet
features.
SftpItemCollection items;
// get all items of current directory recursively
// (items from subdirectories are returned as well)
items = sftp.GetItems("*");
// get all ".txt" files of "/MyData" directory only
// (files from subdirectories are not returned)
items = sftp.GetItems("/MyData/*.txt", TraversalMode.MatchFilesShallow);
// get all ".txt" files under "/MyData" directory
// (files from subdirectories are returned as well)
items = sftp.GetItems("/MyData/*.txt", TraversalMode.MatchFilesDeep);
// initialize a file set
var fileSet = new Rebex.IO.FileSet("/MyData");
fileSet.Include("Web");
fileSet.Exclude("Web/Images");
// get all items defined by the file set
items = sftp.GetItems(fileSet);
Dim items As SftpItemCollection
' get all items of current directory recursively
' (items from subdirectories are returned as well)
items = sftp.GetItems("*")
' get all ".txt" files of "/MyData" directory only
' (files from subdirectories are not returned)
items = sftp.GetItems("/MyData/*.txt", TraversalMode.MatchFilesShallow)
' get all ".txt" files under "/MyData" directory
' (files from subdirectories are returned as well)
items = sftp.GetItems("/MyData/*.txt", TraversalMode.MatchFilesDeep)
' initialize a file set
Dim fileSet = New Rebex.IO.FileSet("/MyData")
fileSet.Include("Web")
fileSet.Exclude("Web/Images")
' get all items defined by the file set
items = sftp.GetItems(fileSet)
Listing directory content - on the fly
All item listing methods raise a ListItemReceived
event when an item is received.
This is very useful when working with huge directory listings because it makes it possible to display items as they arrive.
It also makes it possible to filter item listings using any custom criteria (such as last write time).
Custom item listing filter implementation:
void client_ListItemReceived(object sender, SftpListItemReceivedEventArgs e)
{
// ignore ale items older than 7 days
if (e.Item.LastWriteTime < DateTime.Now.Date.AddDays(-7))
e.Ignore();
}
Sub client_ListItemReceived(ByVal sender As Object, ByVal e As SftpListItemReceivedEventArgs)
' ignore ale items older than 7 days
If e.Item.LastWriteTime < DateTime.Now.Date.AddDays(-7) Then
e.Ignore()
End If
End Sub
Registering the event handler:
// register ListItemReceived event handler which is raised
// when an item description is received from the server
sftp.ListItemReceived += client_ListItemReceived;
// get items of current directory filtered by the event handler
SftpItemCollection items = sftp.GetList();
' register ListItemReceived event handler which is raised
' when an item description is received from the server
AddHandler sftp.ListItemReceived, AddressOf client_ListItemReceived
' get items of current directory filtered by the event handler
Dim items As SftpItemCollection = sftp.GetList()
Getting raw directory listing
The GetRawList
method provides a list of files and directories in a raw Unix-like text format
(similar to "ls -l" command and server-dependent):
-rw-r--r-- 1 tester0 tester0 17 May 16 15:00 file.pdf drwxr-xr-x 2 tester0 tester0 4096 May 16 15:00 Web -rw-r--r-- 1 tester0 tester0 17 May 16 15:00 file.txt
// get unix-like listing of items within the current directory
string[] currentItems = sftp.GetRawList();
// get unix-like listing of text files within the specified directory
string[] textFiles = sftp.GetRawList("/MyData/*.txt");
// simply print the directory listing
Console.WriteLine(string.Join("\r\n", currentItems));
' get unix-like listing of items within the current directory
Dim currentItems As String() = sftp.GetRawList()
' get unix-like listing of text files within the specified directory
Dim textFiles As String() = sftp.GetRawList("/MyData/*.txt")
' simply print the directory listing
Console.WriteLine(String.Join(vbCrLf, currentItems))
Finding files
To find a file or multiple files on the remote host, use GetList
and GetItems
methods.
The GetList
method only searching in one particular folder, while GetItems
method
can search its subfolders as well:
SftpItemCollection items;
// find all "*.txt" files in "/MyData" directory only
items = sftp.GetList("/MyData/*.txt");
// find all "*.txt" files in "/MyData" directory and its subdirectories
items = sftp.GetItems("/MyData/*.txt", TraversalMode.MatchFilesDeep);
Dim items As SftpItemCollection
' find all "*.txt" files in "/MyData" directory only
items = sftp.GetList("/MyData/*.txt")
' find all "*.txt" files in "/MyData" directory and its subdirectories
items = sftp.GetItems("/MyData/*.txt", TraversalMode.MatchFilesDeep)
Creating a directory
To create a new remote directory, use CreateDirectory
method.
It returns the absolute path of the newly created directory.
// create new remote directory
string newDir = sftp.CreateDirectory("/MyData/Exports");
// notify the user
Console.WriteLine("New directory created: {0}", newDir);
' create new directory
Dim newDir As String = sftp.CreateDirectory("/MyData/Exports")
' notify the user
Console.WriteLine("New directory created: {0}", newDir)
Deleting a directory
To delete an empty remote directory, use RemoveDirectory
method.
Delete
method instead.
// delete remote directory if it doesn't exist locally
if (!Directory.Exists(@"C:\MyData\Exports"))
{
// fails if not empty
sftp.RemoveDirectory("/MyData/Exports");
// notify the user
// ...
}
' delete remote directory if it doesn't exist locally
If Not Directory.Exists("C:\MyData\Exports") Then
' fails if not empty
sftp.RemoveDirectory("/MyData/Exports")
' notify the user
' ...
End If
Deleting directories recursively
To delete non-empty remote directory or multiple files, use Delete
method.
Be careful - this is a very powerful method.
// delete whole remote directory
// (deletes "/MyData/Temp" directory itself as well)
sftp.Delete("/MyData/Temp", TraversalMode.Recursive);
// delete content of remote directory
// (keep "/MyData" directory itself)
sftp.Delete("/MyData/*", TraversalMode.Recursive);
// delete all ".txt" files in "/MyData"
sftp.Delete("/MyData/*.txt", TraversalMode.MatchFilesShallow);
' delete whole remote directory
' (deletes "/MyData/Temp" directory itself as well)
sftp.Delete("/MyData/Temp", TraversalMode.Recursive)
' delete content of remote directory
' (keep "/MyData" directory itself)
sftp.Delete("/MyData/*", TraversalMode.Recursive)
' delete all ".txt" files in "/MyData"
sftp.Delete("/MyData/*.txt", TraversalMode.MatchFilesShallow)
Renaming/moving a directory
To rename a directory, use Rename
method.
It can be used for moving a remote directory to another location at the server as well.
// rename a remote directory
sftp.Rename("/MyData/A", "/MyData/B");
// move a remote directory
sftp.Rename("/MyData/Exports", "/Backups/Exports");
' rename a remote directory
sftp.Rename("/MyData/A", "/MyData/B")
' move a remote directory
sftp.Rename("/MyData/Exports", "/Backups/Exports")
Tip: For moving directories between a client and a server,
use Upload
or Download
methods with TransferMethod.Move
argument.
Checking directory existence
To check whether a remote directory already exists, use DirectoryExists
method.
// check whether a remote directory exists
bool exists = sftp.DirectoryExists("/MyData/Exports");
if (exists)
{
// prompt the user
// ...
}
' check whether a remote directory exists
Dim exists = sftp.DirectoryExists("/MyData/Exports")
If exists Then
' prompt the user
' ...
End If
Sorting directory content
GetList
and GetItems
methods return directory items in the
same order as returned by the server, which often means no sorting at all.
To sort the items, use SftpItemCollection
's Sort
method
and FileSystemItemComparer
object.
For more sorting options, see FileSystemItemComparerType
enum.
// get items in the current directory
SftpItemCollection items = sftp.GetList();
// example 1: large files first
items.Sort(new FileSystemItemComparer(FileSystemItemComparerType.Length));
// example 2: order by multiple fields
// (directories first, then order by file name)
items.Sort(new MultiComparer(
new FileSystemItemComparer(FileSystemItemComparerType.FileType),
new FileSystemItemComparer(FileSystemItemComparerType.Name)));
' get items in the current directory
Dim items As SftpItemCollection = sftp.GetList()
' example 1: large files first
items.Sort(New FileSystemItemComparer(FileSystemItemComparerType.Length))
' example 2: order by multiple fields
' (directories first, then order by file name)
items.Sort(New MultiComparer(
New FileSystemItemComparer(FileSystemItemComparerType.FileType),
New FileSystemItemComparer(FileSystemItemComparerType.Name)))
LINQ support - IEnumerable<T> collection
The SftpItemCollection
object returned by GetList
and GetItems
methods
implements IEnumerable<SftpItem>
to support LINQ queries:
As it implements IEnumerable<FileSystemItem>
as well (part of common SFTP and FTP API),
casting it explicitly to IEnumerable<SftpItem>
might be necessary in order to use the proper LINQ extension methods.
You can achieve this by calling Cast<SftpItem>
method.
DateTime dt = DateTime.Now.Date.AddDays(-7);
// get all ".txt" files not older than 7 days sorted by path
// from current directory using LINQ methods
var files1 =
sftp.GetList("*.txt").Cast<SftpItem>().
Where(item => item.IsFile && item.LastWriteTime > dt).
OrderBy(item => item.Path);
// get all ".txt" files not older than 7 days sorted by path
// anywhere under current directory using a LINQ query
var items = sftp.GetItems("*.txt", TraversalMode.MatchFilesDeep);
var files2 =
from SftpItem item in items
where item.IsFile && item.LastWriteTime > dt
orderby item.Path
select item;
Dim dt = DateTime.Now.Date.AddDays(-7)
' get all ".txt" files not older than 7 days sorted by path
' from current directory using LINQ
Dim files1 =
sftp.GetList("*.txt").Cast(Of SftpItem).
Where(Function(item) item.IsFile AndAlso item.LastWriteTime > dt).
OrderBy(Function(item) item.Path)
' get all ".txt" files not older than 7 days sorted by path
' anywhere under current directory using LINQ to SQL
Dim items = sftp.GetItems("*.txt", TraversalMode.MatchFilesDeep)
Dim files2 =
From item As SftpItem In items
Where item.IsFile AndAlso item.LastWriteTime > dt
Order By item.Path
Select item
Back to feature list...