簡體   English   中英

是否可以直接從 MemoryStream 將 CSV 文件上傳到 SFTP 服務器?

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

每當我嘗試使用.csv文件擴展.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已經返回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");
}

您可以避免像這樣不必要地使用內存流:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM