gpt4 book ai didi

c# - StreamWriter 错误字符

转载 作者:行者123 更新时间:2023-12-02 17:59:15 27 4
gpt4 key购买 nike

遇到一个问题,streamwriter 在我正在生成的 csv 中生成错误的字符。字符  只出现在文件的开头:

5,"GEN",555555555,,"Evan","Smith",,,,,,,,,,,,,,,,,,,,,,,,,"email@someplace.com"
5,"GEN",555555555,,"Dorathy","Smith",,,,,,,,,,,,,,,,,,,,,,,,,"email@someplace.com"
5,"GEN",555555555,,"Marvin","Smith",,,,,,,,,,,,,,,,,,,,,,,,,"email@someplace.com"
....

在我看来像是编码问题。我尝试过不同的编码和正则表达式来清理字符串,但运气不佳。这是预览代码(虽然并不复杂)。它还作为网络进程运行。

string fileName = includeEmail == false ? "attachment; filename=stuacct_batch.txt" : "attachment; filename=rentals.csv";
Context.Response.Clear();
Context.Response.AddHeader("content-disposition", fileName);
Context.Response.ContentType = includeEmail == false ? "text/plain" : "text/csv";

using (StreamWriter sw = new StreamWriter(Response.OutputStream, Encoding.UTF8))
{
string line = "";
foreach (Student s in students)
{
// ... some logic above that that's misc. to this problem
line = "5,\"GEN\"," + s.StudentNumber + ",,\"" + s.FirstName + "\",\"" + s.LastName + "\",,,,,,,,,,,,,,,,,,,,,,,,,\"" + s.Email + "\"";
sw.WriteLine(line);
}
}

Context.Response.End();
Context.Response.Flush();
Context.ApplicationInstance.CompleteRequest();

最佳答案

您已指定要对流使用 UTF-8 编码,并且这些初始字节是有效的 UTF-8 字节顺序标记 (BOM)。问题显然是您的查看器/编辑器无法正确解码 UTF-8 流。如果仅 BOM 是问题所在,并且您想要创建没有 BOM 的流,则可以创建您自己的 UTF8Encoding 实例。类:

var encoding = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false);
using (StreamWriter sw = new StreamWriter(Response.OutputStream, encoding)) ...

如果您确实想使用 ASCII 数据,您应该使用该编码:

using (StreamWriter sw = new StreamWriter(Response.OutputStream, Encoding.ASCII)) ...

关于c# - StreamWriter 错误字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10318850/

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