当我使用SSH.NET使用SFTP传输文件时,我观察到一些奇怪的行为.我正在使用SFTP将
XML文件传输到另一个服务(我无法控制)进行处理.如果我使用SftpClient.WriteallBytes,服务会抱怨该文件不是有效的XML.如果我先写入临时文件,然后使用SftpClient.UploadFile,则传输成功.
发生了什么?
使用.WriteallBytes:
public void Send(string remoteFilePath,byte[] contents) { using(var client = new SftpClient(new ConnectionInfo(/* username password etc.*/))) { client.Connect(); client.WriteallBytes(remoteFilePath,contents); } }
使用.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); } }
编辑:
请问评论中我将如何将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(); }
解决方法
我可以使用NuGet的SSH.NET 2016.0.0重现您的问题.但不是2016.1.0-beta1.
检查代码,我可以看到SftpFileStream(WriteallBytes使用的东西)始终保持写入相同(起始)的数据.
看来你正在遭受这个bug:
https://github.com/sshnet/SSH.NET/issues/70
虽然错误描述并不清楚它是你的问题,修复它的提交符合我发现的问题:
Take into account the offset in SftpFileStream.Write(byte[] buffer,int offset,int count) when not writing to the buffer. Fixes issue #70.
回答你的问题:这些方法确实应该表现得相似.
除了SftpClient.UploadFile针对大量数据的上传进行了优化,而SftpClient.WriteallBytes则没有.所以底层实现是非常不同的.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。