I'm a little bit confused about the file encoding. I want to change it. Here is my code:
public class ChangeFileEncoding
{
private const int BUFFER_SIZE = 15000;
public static void ChangeEncoding(string source, Encoding destinationEncoding)
{
var currentEncoding = GetFileEncoding(source);
string destination = Path.GetDirectoryName(source) +@"\"+ Guid.NewGuid().ToString() + Path.GetExtension(source);
using (var reader = new StreamReader(source, currentEncoding))
{
using (var writer =new StreamWriter(File.OpenWrite(destination),destinationEncoding ))
{
char[] buffer = new char[BUFFER_SIZE];
int charsRead;
while ((charsRead = reader.Read(buffer, 0, buffer.Length)) > 0)
{
writer.Write(buffer, 0, charsRead);
}
}
}
File.Delete(source);
File.Move(destination, source);
}
public static Encoding GetFileEncoding(string srcFile)
{
using (var reader = new StreamReader(srcFile))
{
reader.Peek();
return reader.CurrentEncoding;
}
}
}
And in the Program.cs I have the code:
string file = @"D:\path\test.txt";
Console.WriteLine(ChangeFileEncoding.GetFileEncoding(file).EncodingName);
ChangeFileEncoding.ChangeEncoding(file, new System.Text.ASCIIEncoding());
Console.WriteLine(ChangeFileEncoding.GetFileEncoding(file).EncodingName);
And the text printed in my console is:
Unicode (UTF-8)
Unicode (UTF-8)
Why the file's encoding it's not changed? I am wrong in changing the file's encoding?
Regards