Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wrong byte-length when using csvhelper and memorystream

I am using CSVHelper to convert a list of objects to csv and then save it to an FTP - but the length of the content is not correctly calculated so the end of the content is truncated. Can anybody see what I am doing wrong here;

    using (var memoryStream = new MemoryStream())
      {
        using (var streamWriter = new StreamWriter(memoryStream))
        {
          using (var csvWriter = new CsvWriter(streamWriter))
          {
            csvWriter.Configuration.Delimiter = ";";
            csvWriter.Configuration.HasHeaderRecord = false;
            csvWriter.WriteRecords<MyObject>(myObjectList);

            var request = (FtpWebRequest)WebRequest.Create(".../my.csv");
            request.Method = WebRequestMethods.Ftp.UploadFile;
            request.Credentials = new NetworkCredential("user", "pass");
            request.ContentLength = memoryStream.Length;
            byte[] fileContents = memoryStream.ToArray();
            Stream requestStream = request.GetRequestStream();
            requestStream.Write(fileContents, 0, fileContents.Length);
            requestStream.Close();
            FtpWebResponse response = (FtpWebResponse)request.GetResponse();
            response.Close();
          }
        }
      }
    }

Both memoryStream.Length and fileContents.Length gives me the same number but it is to small compared to the amount of real data.

like image 324
keysersoze Avatar asked Oct 27 '25 10:10

keysersoze


1 Answers

You're not flushing the writers data to the stream. A StreamWriter will flush itself when it's full, but you need to manually flush when you're done writing to it.

streamWriter.Flush();
like image 143
Josh Close Avatar answered Oct 28 '25 22:10

Josh Close



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!