gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 23:48:00 24 4
gpt4 key购买 nike

我正在打开一个文件,并逐行读取它。每行都被更改,然后写入另一个文件。我需要将编码更改为 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
}

关于c# - 如何更改此文件的编码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26938349/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com