Write string to a stream using utf16 encoding

10,488
System.Text.Encoding encoding = System.Text.Encoding.Unicode; 
BinaryWriter bw = new BinaryWriter (pStream, encoding);

See here.

Share:
10,488
apocalypse
Author by

apocalypse

:F

Updated on November 21, 2022

Comments

  • apocalypse
    apocalypse over 1 year

    My code:

            public static void DoStrumienia (string pString, Stream pStream)
            {
                  if (pStream == null) throw new ArgumentNullException ();
    
                  BinaryWriter bw = new BinaryWriter (pStream);
    
                  int rozmiar = pString.Length;
                  bw.Write (rozmiar);
    
                  for (int i = 0; i < rozmiar; i++)
                  {
                        bw.Write (pString[i]);
                  }
    
                  bw.Flush ();
            }
    

    It writes string to a stream, but it writes using UTF8 encoding. How to it with UTF16?

    • M.Babcock
      M.Babcock about 12 years
      Why are you writing one character at a time?
    • apocalypse
      apocalypse about 12 years
      Because it's the only way what I know for now.
  • apocalypse
    apocalypse about 12 years
    Why i should use Big Endian encoding? It doesnt make sense to me. I just fixed line: bw.Write (pString[i]); to bw.Write ((ushort)pString[i]); and maybe it will be works.
  • apocalypse
    apocalypse about 12 years
    x86, so i use LE. Just casting to a USHORT make everything OK. Looks like BinaryWriter uses UTF8 encodinf for chars. So ushort prevents it, and all works ok. Anyway thank you for ur answer.
  • Icarus
    Icarus about 12 years
    @zgnilec System.Text.Encoding.Unicode should be UTF-16 (little endian) encoding. Use that one if that's what you need.
  • apocalypse
    apocalypse about 12 years
    Oh sorry, im little tired, didnt even looked u set stream to specyfic encoding :) Just thought u did conversion or smth:O need go to sleep, u got best answer, thank you.