gpt4 book ai didi

c# - 为什么我的 CSV 文件末尾有一百万个空字符

转载 作者:太空狗 更新时间:2023-10-29 19:55:48 25 4
gpt4 key购买 nike

我正在动态生成数据的 CSV 导出。为此,我获取项目的哈希集,然后逐行转换它们并将它们写入 MemoryStream,MemoryStream 又作为 FileResult 发送到客户端。问题是文件末尾有大约一百万个 NULL 字符,我猜这些字符的数量等于哈希集中的项目数量。但它们位于文件的末尾,而不是每行的末尾。

无论如何,代码是这样的:

Controller 方法:

public ActionResult ExportList(ListExportModel model)
{
System.IO.MemoryStream ms = ls.ExportListToCsv(model,Server.MapPath("~/uploads"));
return File(ms.GetBuffer(),"text/csv",model.MailingList.ListName + ".csv");
}

ExportListToCsv 方法

public MemoryStream ExportListToCsv(ListExportModel model, string folderpath)
{
MemoryStream stream = new MemoryStream();
StreamWriter writer = new StreamWriter(stream);

writer.WriteLine(string.Join(",", model.Columns));
var data = GetListItemsFromCsv(model.ListId, folderpath);

XmlDocument doc = new XmlDocument();
// Parallel.ForEach(data, (li) =>
foreach (var li in data)
{
string line = "";
foreach (var field in model.Columns)
{
doc.LoadXml(li.CustomFields);
switch (field)
{
//our standard fields
case "email":
line += li.Email + ",";
break;
case "tel":
line += li.Tel + ",";
break;

default:
line += (doc.SelectNodes("//" + field))[0].Value + ",";
break;
}
}

writer.WriteLine(line.TrimEnd(','));
}
writer.Flush();
stream.Position = 0;
return stream;
}

和文件(所有虚拟数据,截图制作过程中没有真人受到伤害): enter image description here

注意:无论我是否使用,我都会得到相同的结果

writer.Flush()

stream.Position = 0

或不

最佳答案

您正在调用 GetBuffer() 而不是 ToArray()

参见:http://msdn.microsoft.com/en-us/library/system.io.memorystream.toarray

This method omits unused bytes in MemoryStream from the array. To get the entire buffer, use the GetBuffer method.

This method returns a copy of the contents of the MemoryStream as a byte array. If the current instance was constructed on a provided byte array, a copy of the section of the array to which this instance has access is returned. See the MemoryStream constructor for details.

关于c# - 为什么我的 CSV 文件末尾有一百万个空字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27268994/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com