我编写了此代码,用于从CSV
DataGridView
文件
var dialog = new SaveFileDialog { Filter = @"Csv File|*.csv" };
var result = dialog.ShowDialog();
if (result != DialogResult.OK)
return;
var builder = new StringBuilder();
var rowcount = dgvSum.Rows.Count;
var columncount = dgvSum.Columns.Count;
var headerCols = new List<string>();
for (var j = 0; j < columncount - 1; j++)
{
headerCols.Add(dgvSum.Columns[j].HeaderText);
}
builder.AppendLine(string.Join(";", headerCols.ToArray()));
for (var i = 0; i < rowcount - 1; i++)
{
var cols = new List<string>();
for (var j = 0; j < columncount - 1; j++)
{
cols.Add(dgvSum.Rows[i].Cells[j].Value.ToString());
}
builder.AppendLine(string.Join(",", cols.ToArray()));
}
File.WriteAllText(dialog.FileName, builder.ToString());
MessageBox.Show(@"Csv file was created.");
但是,我想在我创建的文件中显示Unicode字符。如何转换为UTF-8
?
答案 0 :(得分:0)
试试这个:
System.IO.File.WriteAllBytes(fileLocation, Encoding.UTF8.GetBytes(builder.ToString()));
用法:
WriteAllBytes 方法第二个参数意味着您可以使用包含UTF-8的特定编码从字符串中保存文件。
您可以使用 ReadAllBytes 与字符串块的其他编码进行比较(如果它们是同一个。
string test = "Hello World!\u1255";
string fileLocation = "the file location you want to save";
File.WriteAllBytes(fileLocation , Encoding.UTF8.GetBytes(test));
Assert.AreEqual(Encoding.UTF8.GetBytes(test), file.ReadAllBytes());