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

本文关键字:开头 获取 文件 BinaryWrite Response | 更新日期: 2023-09-27 18:18:56

我想写一个字符串到一个文件,用户可以从我的网站下载。

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应该是什么。我有时也会在我的文件末尾看到垃圾。我怎样才能清除文件开头和结尾的垃圾?

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

这是因为您正在使用二进制格式化程序。试编码。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);

您正在编写的是文本文件吗?只需使用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);