c# - 是否可以直接从 MemoryStream 将 CSV 文件上传到 SFTP 服务器?
问题描述
每当我尝试使用文件扩展名将文件上传到 SFTP 服务器时,该.csv
文件中唯一的内容是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
返回 a Stream
not a MemoryStream
,因此通过切换csvFileWriter
和切换CsvPut()
到MemoryStream
它起作用。
更新使用声明:
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);
}
}
解决方案
看起来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");
}
推荐阅读
- authentication - 在 IIS 下使用 Windows 身份验证对 LDAP 查询进行身份验证
- java - Spring data JPA 将 unsigned BITINT 转换为 Long 而不是 BigInteger
- sql - Postgresql 基于日期聚合值
- mediawiki - 收到错误“internal_api_error_InvalidArgumentException”
- struct - 将 Struct 转移到两个不同的 impl 函数
- javascript - JS(template Literal-)生成html,更新DOM?
- python - 对于我,枚举中的中间件(settings.MIDDLEWARE):TypeError:'NoneType'对象不可迭代
- ruby - Ruby String:存储包含反斜杠和十六进制表示法的字符串
- swift - SwiftUI - 删除单元格之间的空间
- javascript - 如何确保 JavaScript .submit() 尊重附加到表单的事件处理程序