will
will

Reputation: 897

How do I change the encoding on this file?

I'm opening a file, and reading it line by line. Each line is being changed, then written to another file. I need to change the encoding to UTF-16, but I can't find a way to do this. Can anyone help? This is, of course, c#.

using (var inputStream = File.OpenRead(sourceFile))
{
    using (var inputReader = new StreamReader(inputStream))
    {
        using (var outputWriter = File.AppendText(destFile))
        {
            string tempLineValue;
            while (null != (tempLineValue = inputReader.ReadLine()))
            {
                if (tempLineValue != "\t\t\t\t\t")
                {
                    var newEndOfLine = string.Format("{0}Added Info\r\0\n\0", '\0');
                    var firstReplace = tempLineValue.Replace('\t', '\0');
                    var secondReplace = firstReplace + newEndOfLine;
                    outputWriter.WriteLine(secondReplace); 
                }
            }
        }
    }
}

Upvotes: 1

Views: 69

Answers (2)

Nathan A
Nathan A

Reputation: 11339

You can't use File.AppendText. Based on the docs: http://msdn.microsoft.com/en-us/library/system.io.file.appendtext(v=vs.110).aspx, it only outputs UTF-8.

Instead, create your own StreamWriter (http://msdn.microsoft.com/en-us/library/3aadshsx(v=vs.110).aspx), which will allow you to specify whatever encoding you want. Just create a new output stream and do the following:

var outputStream = new FileStream(destFile, FileMode.Append, FileAccess.Write);

using (StreamWriter outputWriter = new StreamWriter(outputStream, Encoding.Unicode))
{
    //do whatever write you want
}

Upvotes: 2

EZI
EZI

Reputation: 15364

You can't do it on the same file (at least without using too complex codes). Create a new file with the encoding you want.

Encoding inEnc = .......; //Encoding.Default
Encoding outEnc = Encoding.Unicode;

File.WriteAllText(outfilename, File.ReadAllText(infilename, inEnc), outEnc);

Upvotes: 1

Related Questions