【发布时间】:2019-12-20 11:58:39
【问题描述】:
我的问题是,当我想将字符串转换为字节数组时,特殊字母转换失败。
喜欢:
在字符串中:
Városmajor在字节数组中:
V�rosmajor
我的代码旨在从数据表中创建一个字符串,然后作为响应 CSV 文件发送。
public ActionResult DownloadCSV(int id)
{
string res = provider.GetCSVtoDownload(id);
byte[] buffer = Encoding.GetEncoding("ISO-8859-1").GetBytes(q);
this.Response.Headers.Add("Content-Disposition", "attachment;data.csv");
this.Response.ContentType = "text/csv";
return File(buffer, "text/csv", "orderdata.csv");
}
public string GetCSVtoDownload(int id)
{
var data = ctx.myDbSet.Find(id);
var dt = new DataTable();
dt.Columns.Add("id", typeof(int));
dt.Columns.Add("name", typeof(string));
object[] o = {
data.id,
data.name,
};
dt.Rows.Add(o);
StringBuilder sb = new StringBuilder();
IEnumerable<string> columnNames = dt.Columns.Cast<DataColumn>().
Select(column => column.ColumnName);
sb.AppendLine(string.Join(",", columnNames));
foreach (DataRow row in dt.Rows)
{
IEnumerable<string> fields = row.ItemArray.Select(field => field.ToString());
sb.AppendLine(string.Join(",", fields));
}
return sb.ToString();
}
我已经尝试过:UTF8 和 ASCII 编码。
【问题讨论】:
-
尝试使用其他编码,如 UTF-8?
-
是的,我已经尝试过了
-
问题:你认为应该输出什么字节?不同的编码/代码页有不同的字节序列,所以:选择是关键。除了“你所期望的”之外,没有“正确”的答案。那么:您希望
é和á的字节序列是什么,表示为十六进制?例如,UTF-8 会分别表示 C3 A9 和 C3 A1 -
你尝试过 Unicode 吗?
-
@useruser 等等...你的意思是在字节数组中?我认为这可能是字节数组下的预期行为?而你需要做的是解码这个字节数组? (不知道对不对)