Wrong byte-length when using csvhelper and memorystream

1.4k views Asked by At

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.

1

There are 1 answers

0
Josh Close On

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