C# .NET - how to encode from Shift-JIS to UTF-16 in C#

Asked By A S on 15-May-07 10:35 AM

We are getting a flat file every day from japan which is encoded as Shift-JIS. I need to convert that to UTF-16 to upload into sql server 2000 database. can you please tell me how to write for that in C# which convert the flat file into UTF-16.


Thank you in advance!

This sample coverts a file's encoding - Peter Bromberg replied to A S on 15-May-07 01:00 PM

using System;
using System.IO;
using System.Text;

public class FileConverter
{
    const int BufferSize = 8096;
   
    public static void Main(string[] args)
    {
        if (args.Length != 2)
        {
            Console.WriteLine
                ("Usage: FileConverter <input file> <output file>");
            return;
        }
       
        // Open a TextReader for the appropriate file
        using (TextReader input = new StreamReader
               (new FileStream (args[0], FileMode.Open),
                Encoding.UTF8))
  // if your desired encoding is not in the enum, you can use Encoding.GetEncoding( ...) and overloads
        {
            // Open a TextWriter for the appropriate file
            using (TextWriter output = new StreamWriter
                   (new FileStream (args[1], FileMode.Create),
                    Encoding.Unicode))
            {

                // Create the buffer
                char[] buffer = new char[BufferSize];
                int len;
               
                // Repeatedly copy data until we've finished
                while ( (len = input.Read (buffer, 0, BufferSize)) > 0)
                {
                    output.Write (buffer, 0, len);
                }
            }
        }
    }
}