我正在使用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都给了我相同的数字,但与实际数据量相比太小了。
Flush
几乎肯定会起到作用。它将在using
子句结束时自动调用。可能您可以通过将csvWriter.WriteRecords
下面的所有代码移至子句后来简化 - 无需显式调用Flush
。 - groverboy