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

一世执手 提交于 2021-02-08 07:28:31

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!