Search code examples
c#sftprebex

unable to save dynamically created MemoryStream with rebex sftp


I'm using StreamWriter to generate a dynamic file and holding it in a MemoryStream. Everything appears to be alright until I go to save the file using rebex sftp.

The example they give on their site works fine:

// upload a text using a MemoryStream 
string message = "Hello from Rebex FTP for .NET!";
byte[] data = System.Text.Encoding.Default.GetBytes(message);
System.IO.MemoryStream ms = new System.IO.MemoryStream(data);
client.PutFile(ms, "message.txt");

However the code below does not:

using (var stream = new MemoryStream())
{
    using (var writer = new StreamWriter(stream))
    {
        writer.AutoFlush = true;
        writer.Write("test");
    } 
    client.PutFile(stream, "test.txt");
}

The file "test.txt" is saved, however it is empty. Do I need to do more than just enable AutoFlush for this to work?


Solution

  • After writing to the MemoryStream, the stream is positioned at the end. The PutFile method reads from the current position to the end. That's exactly 0 bytes.

    You need to position the stream at the beginning before passing it to PutFile:

        ...
    }
    stream.Seek(0, SeekOrigin.Begin);
    client.PutFile(stream, "test.txt");
    

    You may also need to prevent the StreamWriter from disposing the MemoryStream:

    var writer = new StreamWriter(stream);
    writer.Write("test");
    writer.Flush();
    stream.Seek(0, SeekOrigin.Begin);
    client.PutFile(stream, "test.txt");