【发布时间】:2013-10-16 11:20:18
【问题描述】:
这是我的代码
static void Write(DataTable dt, string outputFilePath)
{
int[] maxLengths = new int[dt.Columns.Count];
for (int i = 0; i < dt.Columns.Count; i++)
{
maxLengths[i] = dt.Columns[i].ColumnName.Length;
foreach (DataRow row in dt.Rows)
{
if (!row.IsNull(i))
{
int length = row[i].ToString().Length;
if (length > maxLengths[i])
{
maxLengths[i] = length;
}
}
}
}
using (StreamWriter sw = new StreamWriter(outputFilePath, false))
{
sw.Write(new byte[]{0xff,0xfe});
foreach (DataRow row in dt.Rows)
{
for (int i = 0; i < dt.Columns.Count; i++)
{
if (!row.IsNull(i))
{
sw.Write(row[i].ToString() + " ");
}
}
sw.WriteLine();
}
}
}
我想在文本文件的开头添加 2 个字节。
sw.Write(new byte[]{0xff,0xfe});
问题是当我用十六进制打开时,我看不到这 2 个字节。 但我在文本文件本身上看到了这些 :\
任何解决方案请帮助。 它假设看起来像这样
【问题讨论】:
-
为什么要写一个UTF-16 BOM,然后把内容输出为UTF-8?我的猜测是该文件应该是 UTF-16,而您应该只使用
new StreamWriter(..., Encoding.Unicode)。