C# Save a file with Korean encoding

不想你离开。 提交于 2019-12-24 00:02:15

问题


Have the following codeblock that saves a file with the selected encoding. When the file is opened in a text editor it shows the encoding as ASCII..

StringBuilder sb = new StringBuilder();
sb.Append(); // Lots of korean text here

Encoding enc = Encoding.GetEncoding(51949);
using (StreamWriter sw = new StreamWriter(fileName, false, enc))
{
    sw.Write(sb.ToString());
sw.Flush();
sw.Close();
}

Can anyone help?

Thanks


回答1:


You have to use UnicodeEncoding while saving the file, and for unicode Encoding, this the below code, and modify as per your need. try this:

 UnicodeEncoding unicode = new UnicodeEncoding();

        // Create a string that contains Unicode characters.
        String unicodeString =
            "This Unicode string contains two characters " +
            "with codes outside the traditional ASCII code range, " +
            "Pi (\u03a0) and Sigma (\u03a3).";
        Console.WriteLine("Original string:");
        Console.WriteLine(unicodeString);

        // Encode the string.
        Byte[] encodedBytes = unicode.GetBytes(unicodeString);
        Console.WriteLine();
        Console.WriteLine("Encoded bytes:");
        foreach (Byte b in encodedBytes) {
            Console.Write("[{0}]", b);
        }
        Console.WriteLine();

        // Decode bytes back to string.
        // Notice Pi and Sigma characters are still present.
        String decodedString = unicode.GetString(encodedBytes);
        Console.WriteLine();
        Console.WriteLine("Decoded bytes:");
        Console.WriteLine(decodedString);



回答2:


When the file is opened in a text editor it shows the encoding as ASCII..

There is nothing in the file that tells the text editor the encoding.

You need to sup0ply metadata in some way. Either by getting the user to use some "open with selected encoding" option in the text editor (if it has one), or use a different encoding in the file (eg. UTF-8 or -16 with a BOM) that includes the code points you need, and the text editor can detect.




回答3:


Try replacing

Encoding enc = Encoding.GetEncoding(51949);

with Encoding enc = Encoding.Unicode;

or Encoding enc = Encoding.UTF8;




回答4:


You should use Encoding.Unicode - so the output will include the BOM and will be encoded in Unicode multi-byte.



来源:https://stackoverflow.com/questions/6621532/c-sharp-save-a-file-with-korean-encoding

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!