当我使用 SSH.NET 通过 SFTP 传输文件时,我观察到一些奇怪的行为。我正在使用 SFTP 将 XML 文件传输到另一个服务(我不控制)进行处理。如果我使用SftpClient.WriteAllBytes
该服务抱怨该文件不是有效的 XML。如果我首先写入临时文件然后使用SftpClient.UploadFile
转移成功。
发生了什么?
Using .WriteAllBytes
:
public void Send(string remoteFilePath, byte[] contents)
{
using(var client = new SftpClient(new ConnectionInfo(/* username password etc.*/)))
{
client.Connect();
client.WriteAllBytes(remoteFilePath, contents);
}
}
Using .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(/* username password etc.*/)))
{
client.Connect();
client.UploadFile(fs, targetPath);
}
}
Edit:Will 在评论中询问我如何将 XML 转换为字节数组。我认为这不相关,但话又说回来,我是问这个问题的人......:P
// somewhere else:
// XDocument xdoc = CreateXDoc();
using(var st = new MemoryStream())
{
using(var xw = XmlWriter.Create(st, new XmlWriterSettings { Encoding = Encoding.UTF8, Indent = true }))
{
xdoc.WriteTo(xw);
}
return st.ToArray();
}