Skip to main content
 首页 » 编程设计

c#之如何更改此文件的编码

2024年08月12日57落叶

我正在打开一个文件,并逐行读取它。每行都被更改,然后写入另一个文件。我需要将编码更改为 UTF-16,但我找不到执行此操作的方法。谁能帮忙?这当然是 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);  
                } 
            } 
        } 
    } 
} 

请您参考如下方法:

您不能使用 File.AppendText。基于文档:http://msdn.microsoft.com/en-us/library/system.io.file.appendtext(v=vs.110).aspx ,它只输出 UTF-8。

相反,创建您自己的 StreamWriter ( http://msdn.microsoft.com/en-us/library/3aadshsx(v=vs.110).aspx ),这将允许您指定您想要的任何编码。只需创建一个新的输出流并执行以下操作:

var outputStream = new FileStream(destFile, FileMode.Append, FileAccess.Write); 
 
using (StreamWriter outputWriter = new StreamWriter(outputStream, Encoding.Unicode)) 
{ 
    //do whatever write you want 
}