StreamWriter错误的字符

时间:2012-04-25 15:31:21

标签: c#

在我正在制作的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();

2 个答案:

答案 0 :(得分:5)

您已指定要对流使用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)) ...

答案 1 :(得分:0)

这些可能是指定文件是unicode而不是ansi的字符。

您是否在文本编辑器中将文件作为ANSI文件打开?如果是这样,那就是你看到角色的原因。尝试将其打开为unicode,或将您的编码设置为unicode。