3

我正在使用 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 都给了我相同的数字,但与实际数据量相比它太小了。

4

1 回答 1

5

您不会将编写器数据刷新到流中。AStreamWriter写满时会自行刷新,但您需要在完成写入后手动刷新。

streamWriter.Flush();
于 2014-04-10T21:06:20.120 回答