title: Change encoding of a text file from ANSI to UTF8 without affecting any chars of the file in C#!
body: <p>Can anyone help me out? I tried a lot of different ways, but I have had no luck getting the desired result. I just want to change the encoding of an existing text[.txt] file from ANSI to UTF8 which contains chars like ö, ü etc. When I do it manually by opening that text file in edit mode and then FILE=>SAVE AS, it is shows ANSI in the Encoding list. Using this, I am able to change its Encoding from ANSI to UTF8, and it is not changing any contents/chars in this case. But when do it in using CODE, it's not working.</p>
  
  <p>==> First Way I used to achieve that by following Code:</p>
  
  <pre><code>if (!System.IO.Directory.Exists(System.Windows.Forms.Application.StartupPath + "\\Temp"))
  {
      System.IO.Directory.CreateDirectory(System.Windows.Forms.Application.StartupPath + "\\Temp");
  }
  string destPath = System.Windows.Forms.Application.StartupPath + "\\Temp\\temporarytextfile.txt";
  
  File.WriteAllText(destPath, File.ReadAllText(path, Encoding.Default), Encoding.UTF8);
  </code></pre>
  
  <p>==> 2nd Alternative which I used:</p>
  
  <pre><code>using (Stream fileStream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
  {
      using (Stream destStream = new FileStream(destPath, FileMode.Create, FileAccess.Write, FileShare.ReadWrite))
      {
          using (var reader = new BinaryReader(fileStream, Encoding.Default))
          {
              using (var writer = new BinaryWriter(destStream, Encoding.UTF8))
              {
                  var srcBytes = new byte[fileStream.Length];
                  reader.Read(srcBytes, 0, srcBytes.Length);
                  writer.Write(srcBytes);
  
              }
          }
      }
  }
  </code></pre>
  
  <p>==> 3rd Alternative I used:</p>
  
  <pre><code>System.IO.StreamWriter file = new System.IO.StreamWriter(destPath, true, Encoding.Default);
  using (StreamReader sr = new StreamReader(path, Encoding.UTF8, true))
  {
      String line1;
      while ((line1 = sr.ReadLine()) != null)
      {
          file.WriteLine(line1);
      }
  }
  
  file.Close();
  </code></pre>
  
  <p>But unfortunately, none of the above solutions worked for me.</p>