【问题标题】:Save from SQL table to a text file Through Data Table and stream writer [duplicate]通过数据表和流写入器从 SQL 表保存到文本文件 [重复]
【发布时间】: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)

标签: c# sql


【解决方案1】:

试试这样:

sw.Write(new char[]{(char)0xff , (char)0xfe});

在参数中没有使用字节数组写入的实现:http://msdn.microsoft.com/en-us/library/system.io.streamwriter.write.aspx

所以它使用 Object 参数并调用他的 ToString() 方法

【讨论】:

猜你喜欢
  • 2012-01-18
  • 1970-01-01
  • 1970-01-01
  • 2013-09-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-02-02
  • 1970-01-01
相关资源
最近更新 更多