title: Convert.FromBase64String returns unicode sometimes, or UTF-8
body: <p>Sometimes the byte array b64 is UTF-8, and other times is UTF-16.  I keep reading online that C# strings are always UTF-16, but that is not the case for me here.  Why is this happening, and how do I fix it?  I have a simple method for converting a base64 string to a normal string:</p>
  
  <pre><code>public static string FromBase64(this string input)
  {
      String corrected = new string(input.ToCharArray());
      byte[] b64 = Convert.FromBase64String(corrected);
      if (b64[1] == 0)
      {
          return System.Text.Encoding.Unicode.GetString(b64);
      }
      else
      {
          return System.Text.Encoding.UTF8.GetString(b64);
      }
  
  }
  </code></pre>
  
  <p>The same thing is happening to my base 64 encoder:</p>
  
  <pre><code>public static string ToBase64(this string input)
  {
      String b64 = Convert.ToBase64String(input.GetBytes());
      return b64;
  }
  
  public static byte[] GetBytes(this string str)
  {
      byte[] bytes = new byte[str.Length * sizeof(char)];
      System.Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length);
      return bytes;
  }
  </code></pre>
  
  <p>Example:
  On my computer, "cABhAHMAcwB3AG8AcgBkADEA" decodes to:</p>
  
  <pre><code>'p','\0','a','\0','s','\0','s','\0','w','\0','o','\0','r','\0','d','\0','1','\0'
  </code></pre>
  
  <p>But on my coworkers computer it is:</p>
  
  <pre><code>'p','a','s','s','w','o','r','d','1'
  </code></pre>
  
  <p>Edit:</p>
  
  <p>I know that the string I create comes from a textbox, and that the file where I am saving it to is always going to be UTF-8, so everything is pointing to the Convert method causing my encoding switch.</p>
  
  <p>Update:</p>
  
  <p>After digging in further, it appears that my coworker had a very important line commented in his version of the code, the one that saves the value read from file to the hashtable.  The default value I was using is a UTF-8 base64 value, so I am going to correct the default, to a utf-16 value, then I can clean up the code removing any UTF8 references.</p>
  
  <p>Also, I had been naively using the UTF-8 base64 encoding I had retrieved from a website, not realizing what I was getting myself into.  The funny part is I would never have found that fact if my coworker hadn't commented the line that saves the values from the file.</p>
  
  <p>Final version of the code:</p>
  
  <pre><code>public static string FromBase64(this string input)
  {
      byte[] b64 = Convert.FromBase64String(input);
      return System.Text.Encoding.Unicode.GetString(b64);
  }
  
  public static string ToBase64(this string input)
  {
      String b64 = Convert.ToBase64String(input.GetBytes());
      return b64;
  }
  
  public static byte[] GetBytes(this string str)
  {
      return System.Text.Encoding.Unicode.GetBytes(str);
  }
  </code></pre>