每当我尝试将文件扩展名为.csv
的文件上传到SFTP服务器时,该文件中唯一的内容就是System.IO.MemoryStream
。如果是.txt
扩展名,它将在文件中包含所有值。我可以手动将.txt
转换为.csv
,这很好。是否可以将它作为CSV文件直接上传到SFTP服务器?
SFTP服务正在使用Renci的SSH.NET库。
使用声明:
using (var stream = csvFileWriter.Write(data, new CsvMapper()))
{
byte[] file = Encoding.UTF8.GetBytes(stream.ToString());
sftpService.Put(SftpCredential.Credentials.Id, file, $"/file.csv");
}
SFTP服务:
public void Put(int credentialId, byte[] source, string destination)
{
using (SftpClient client = new SftpClient(GetConnectionInfo(credentialId)))
{
ConnectClient(client);
using (MemoryStream memoryStream = new MemoryStream(source))
{
client.BufferSize = 4 * 1024; // bypass Payload error large files
client.UploadFile(memoryStream, destination);
}
DisconnectClient(client);
}
解决方案:
我使用的csvFilerWriter
返回了Stream
而不是MemoryStream
,因此通过将csvFileWriter
和CsvPut()
切换到MemoryStream
即可。< / p>
使用以下语句更新:
using (var stream = csvFileWriter.Write(data, new CsvMapper()))
{
stream.Position = 0;
sftpService.CsvPut(SftpCredential.credemtoa;s.Id, stream, $"/file.csv");
}
更新的SFTP服务:
public void CsvPut(int credentialId, MemoryStream source, string destination)
{
using (SftpClient client = new SftpClient(GetConnectionInfo(credentialId)))
{
ConnectClient(client);
client.BufferSize = 4 * 1024; //bypass Payload error large files
client.UploadFile(source, destination);
DisconnectClient(client);
}
}
答案 0 :(得分:2)
看起来csvFileWriter.Write
已经返回MemoryStream
。并且其ToString
返回"System.IO.MemoryStream"
字符串。这就是问题的根源。
另外,由于您已经拥有MemoryStream
,将其复制到另一个MemoryStream
并直接上载是一个过大的杀伤力。您要一遍又一遍地复制数据,这只是浪费内存。
赞:
var stream = csvFileWriter.Write(data, new CsvMapper());
stream.Position = 0;
client.UploadFile(stream, destination);
另请参阅:
上传内存数据的简单测试代码:
var stream = new MemoryStream();
stream.Write(Encoding.UTF8.GetBytes("this is test"));
stream.Position = 0;
using (var client = new SftpClient("example.com", "username", "password"))
{
client.Connect();
client.UploadFile(stream, "/remote/path/file.txt");
}
答案 1 :(得分:-1)
您可以避免像这样不必要地使用内存流:
using (var sftp = new SftpClient(GetConnectionInfo(SftpCredential.GetById(credentialId).Id))))
{
sftp.Connect();
using (var uplfileStream = System.IO.File.OpenRead(fileName))
{
sftp.UploadFile(uplfileStream, fileName, true);
}
sftp.Disconnect();
}