使用csvhelper和memorystream时字节长度错误

时间:2013-12-04 00:52:55

标签: c# streamwriter memorystream ftpwebrequest csvhelper

我正在使用CSVHelper将对象列表转换为csv然后将其保存到FTP - 但是内容的长度未正确计算,因此内容的末尾被截断。谁能看到我在这里做错了什么;

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

memoryStream.Length和fileContents.Length都给出了相同的数字,但与实际数据量相比,它是小的。

1 个答案:

答案 0 :(得分:5)

您没有将作者数据刷新到流中。一个StreamWriter会在它满了时自行冲洗,但是当你写完它时你需要手动冲洗。

streamWriter.Flush();