Response.BinaryWrite() - 在文件开头获取垃圾

时间:2011-12-29 08:00:09

标签: c# asp.net .net

我正在尝试将字符串写入用户可以从我的网站下载的文件。

var tcxString = "Some code to get my string";

byte[] bytes;
MemoryStream cvsStream = new MemoryStream();
BinaryFormatter bf = new BinaryFormatter();
bf.Serialize(cvsStream, tcxString);

cvsStream.Seek(0, SeekOrigin.Begin);
bytes = cvsStream.ToArray();

Response.Clear();
Response.AppendHeader("content-length", cvsStream.Length.ToString());
Response.ContentType = "application/octet-stream";
Response.AppendHeader("content-disposition", "attachment; filename=MyFileName.txt");
Response.BinaryWrite(bytes);

输出变为:

    ÿÿÿÿ          Some code to get my string

我猜这与我的Seek位置有关,但我不知道正确的Seek应该是什么。有时我也会在文件末尾看到垃圾。如何摆脱文件开头和结尾的垃圾?

2 个答案:

答案 0 :(得分:2)

这是因为您正在使用二进制格式化程序。请尝试使用Encoding.GetBytes。

        var tcxString = "Some code to get my string";

        byte[] bytes = Encoding.UTF8.GetBytes(tcxString);

        Response.Clear();
        Response.AppendHeader("content-length", bytes.Length.ToString());
        Response.ContentType = "application/octet-stream";
        Response.AppendHeader("content-disposition", "attachment; filename=MyFileName.txt");
        Response.BinaryWrite(bytes);

此致

答案 1 :(得分:2)

这是你正在写的文本文件吗? 只需使用Response.Write将其内容写入输出流。

string tcxString = "Some code to get my string";

Response.Clear();
Response.ContentType = "text/plain";
Response.AppendHeader("content-disposition", "attachment; filename=MyFileName.txt");
Response.Write(tcxString);