将字符串作为响应标头返回,并将文本文件附件作为不同的编码类型返回

Return a string as a response header with a text file attachment as different encoding types

提问人:dwewers 提问时间:3/3/2023 最后编辑:vimuthdwewers 更新时间:3/3/2023 访问量:96

问:

我正在尝试编写一种方法,当单击链接按钮时,它会下载一个 .txt 文件。我有一个下拉列表,有两个选项,utf-8(默认)和 utf-16。我需要的是将文件保存为utf-16,当它被选中时。但是,它继续将 .txt 文件保存为 utf-8。我不想保存文件的副本并手动选择编码类型,如下所示。

1

我想这样做的原因是,我放入文本文件中的一些数据包含 utf-8 不支持的字符。

我尝试从字符串构建器创建一个字节数组,但这似乎没有改变任何事情。该文件仍以 utf-8 格式保存。我还尝试将字符集更改为Response.Charset = "utf-16"

private void lb_ExportTxtFile_Click(object sender, EventArgs e)
{
    Response.Clear();
    Response.Buffer = true;

        Response.ContentType = "text/plain";
    Response.Charset = "";
    
    this.EnableViewState = false;
    Response.AddHeader("content-disposition", "attachment;filename=MyFile.txt");

    StringBuilder sb = new StringBuilder();
    
    // ## Populate sb ##

    if (EncodingType == "utf-16") {
        // Write the content to the response stream with UTF-16 encoding
        byte[] byteArray = Encoding.Unicode.GetBytes(sb.ToString());
        Response.BinaryWrite(byteArray);
    }
    else {
        Response.Write(sb.ToString());
    }
    
    Response.End();
}
C# asp.net UTF-8 TXT UTF-16

评论

0赞 jdweng 3/3/2023
StreamWriter 有一个编码参数:learn.microsoft.com/en-us/dotnet/api/...

答: 暂无答案