首页 > 解决方案 > 是否可以直接从 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 Streamnot 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);
    }
}

标签: c#csvsftpmemorystreamssh.net

解决方案


看起来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");
}

推荐阅读