问题
I'm truing to send a CSV with csvhelper. But when I send it, it is always empty.
using (var sftProvider =new SFTProvider(Configuration))
using (var csvProvider=new CSVProvider(Configuration))
using (Stream fileStream = new MemoryStream())
{
var sftp = sftProvider.SFTPConnection("", "", "");
var nameFile = "/ethias/"+DateTime.Now.ToString(DateFormatConstants.DATE_FORMAT) + ".csv";
if (sftp.Exists(nameFile))
{
sftProvider.ReadFileSFTP(sftp, nameFile, fileStream);
}
await csvProvider.WriteCsv(new List<EthiasResultDTO>() {ethiasResultDto},fileStream);
sftProvider.UploadFileSFTP(sftp,nameFile,fileStream);
}
The code for the csv:
public async Task WriteCsv<T>(List<T> csvInfo, Stream stream)
{
using(var writer = new StreamWriter(stream, Encoding.UTF8))
using (var csv = new CsvWriter(writer, CultureInfo.InvariantCulture))
{
csv.Configuration.Delimiter = ";";
if ( stream.Length > 0)
{
csv.Configuration.HasHeaderRecord = false;
}
csv.WriteRecords(csvInfo);
}
}
i try serveral things but it always empty file that is create .
回答1:
You have to seek the read pointer of the stream back to beginning after writing to it. This is covered for example in these questions:
Upload data from memory to SFTP server using SSH.NET
Upload from ByteArray/MemoryStream using SSH.NET - File gets created with size 0KB
For that you also have to make sure that the StreamWriter
does not close the memory stream:
Is there any way to close a StreamWriter without closing its BaseStream?
using (var writer = new StreamWriter(stream, Encoding.UTF8, 1024, true))
using (var csv = new CsvWriter(writer, CultureInfo.InvariantCulture))
{
// Write
}
stream.Position = 0;
来源:https://stackoverflow.com/questions/60691827/when-uploading-memory-stream-with-contents-created-by-csvhelper-using-ssh-net-to