2

I am trying to export a CSV file using SQL Server Management Studio 2005 and I have tried clicking on the drop down button next to Save and selecting encoding UTF, but it still saves as UCS-2 little endian encoding.

Is it possible to have it in UTF-8 encoding without having to open with Notepad++ and save as UTF-8? Extra step and all.

4

2 回答 2

1

因为我需要一个应用程序来为我执行此操作,所以我使用 vb 使用以下链接帮助 http://www.vbnettutorial.net/?Id=119&Desc=Export-CSV-from-Dataset How to export a csv file based以编程方式在 SQL 查询上

于 2014-05-07T07:50:19.530 回答
1

由于 MS SQL Server 仅输出为 UCS-2 Little Endian 或 ASII 编码,您可以使用 bcp 调用一个小 C# 程序将其转换为 UTF-8

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace UCS2toUTF8
{
    class Program
    {
        static void Main(string[] args)
        {
            if (args.Length != 1)
            {
                Console.WriteLine("exampe: UCS2toUTF8 [filepath]");
                return;
            }

            var filename = args[0];

            var filestream = File.OpenRead(filename);

            var BOM = new byte[3];

            filestream.Read(BOM, 0, BOM.Length);

            if (BOM[0] != (byte)255 && BOM[1] != (byte)254 ) //0xff 0xfe 0x48
            {
                Console.WriteLine("This isn't UCS-2LE");
                return;
            }else if (BOM[0] == 0xEF && BOM[1] == 0xBB && BOM[2] == 0xBF)
            {
                Console.WriteLine("This is UTF-8");
                return;
            }

            filestream.Close();

            byte[] content = File.ReadAllBytes(filename);

            byte[] utf8Bytes = System.Text.Encoding.Convert(System.Text.Encoding.Unicode, System.Text.Encoding.UTF8, content);

            byte[] newArray = new byte[utf8Bytes.Length - 3];

            Array.Copy(utf8Bytes, 3, newArray, 0, newArray.Length);

            File.WriteAllBytes(filename, newArray);
        }
    }
}

请注意,如果您想要带有 BOM 的 UTF-8,您需要进行一些修改。

于 2015-07-10T08:53:25.097 回答