[英]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
,因此通過將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");
}
您可以避免像這樣不必要地使用內存流:
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.