是否可以直接从 MemoryStream 将 CSV 文件上传到 SFTP 服务器?

Is it possible to upload a CSV file to an SFTP server directly from a MemoryStream?

每当我尝试使用 .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,因此通过将 csvFileWriterCsvPut() 切换为 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 已经 returns MemoryStream。及其 ToString returns "System.IO.MemoryStream" 字符串。那是你问题的根源。

此外,因为您已经有了 MemoryStream,将它复制到另一个 MemoryStream 上就太过分了,直接上传。你在一遍又一遍地复制数据,这只是浪费内存。

像这样:

var stream = csvFileWriter.Write(data, new CsvMapper());
stream.Position = 0;
client.UploadFile(stream, destination); 

另请参阅:

  • When uploading memory stream with contents created by csvhelper using SSH.NET to SFTP server, the uploaded file is empty

上传内存数据的简单测试代码:

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

你可以像这样避免不必要地使用内存流:

        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();
        }