I am observing some strange behavior when I use SSH.NET to transfer files using SFTP. I use SFTP to transfer XML files to another service (which I do not control) for processing. If I use SftpClient.WriteAllBytes, the service complains that the file is not valid XML. If I write to a temporary file first and then use it SftpClient.UploadFile, the transfer will succeed.
What's happening?
Usage .WriteAllBytes:
public void Send(string remoteFilePath, byte[] contents)
{
using(var client = new SftpClient(new ConnectionInfo()))
{
client.Connect();
client.WriteAllBytes(remoteFilePath, contents);
}
}
Usage .UploadFile:
public void Send(string remoteFilePath, byte[] contents)
{
var tempFileName = Path.GetTempFileName();
File.WriteAllBytes(tempFileName, contents);
using(var fs = new FileStream(tempFile, FileMode.Open))
using(var client = new SftpClient(new ConnectionInfo()))
{
client.Connect();
client.UploadFile(fs, targetPath);
}
}
Edit:
Will the comments ask how to turn XML into a byte array. I did not think this was relevant, but again I am the one who asks the question ...: P
using(var st = new MemoryStream())
{
using(var xw = XmlWriter.Create(st, new XmlWriterSettings { Encoding = Encoding.UTF8, Indent = true }))
{
xdoc.WriteTo(xw);
}
return st.ToArray();
}