Uploading a File from a Stream with the FTP Component
In addition to uploading a file from disk using the LocalFile property, the FTP component can upload data directly from a stream. This is useful when the data is generated in memory, or when it comes from a source other than a local file.
To upload from a stream, call the SetUploadStream method with the stream to read from, set the RemoteFile property, and call the Upload method.
FTP ftp = new FTP();
ftp.RemoteHost = "ftp.example.com";
ftp.User = "user";
ftp.Password = "password";
ftp.Logon();
// Upload a string from memory.
byte[] data = Encoding.UTF8.GetBytes("Hello, world!");
ftp.SetUploadStream(new MemoryStream(data));
ftp.RemoteFile = "hello.txt";
ftp.Upload();
ftp.Logoff();
The component reads the stream from its current position to the end, so the stream should be open and normally positioned at the beginning. The same stream is also used by the Append and StoreUnique methods.
Calling SetUploadStream clears the LocalFile property, and setting LocalFile to a non-empty value clears the upload stream. Only one of the two is used as the source of the upload.
Keeping the Stream Open
By default, the component closes the upload stream after the transfer completes. Since a closed stream cannot be read again, SetUploadStream must be called with a new stream before each upload.
To keep the stream open (e.g., to read or reuse it after the upload), set the CloseStreamAfterTransfer configuration setting to false. In this case, the application is responsible for closing the stream.
ftp.Config("CloseStreamAfterTransfer=false");
using (FileStream stream = new FileStream("C:\data\report.csv", FileMode.Open, FileAccess.Read))
{
ftp.SetUploadStream(stream);
ftp.RemoteFile = "report.csv";
ftp.Upload();
}
To download a file to a stream instead, please see the SetDownloadStream method, which works in the same way.
We appreciate your feedback. If you have any questions, comments, or suggestions about this article please contact our support team at support@nsoftware.com.