任何人都可以帮我吗?我尝试了很多不同的方式,但我没有得到理想的结果。我只是想将现有文本[.txt]文件的编码从ANSI更改为UTF8,其中包含像ö,ü等字符。当我通过在编辑模式下打开该文本文件并手动执行FILE => SAVE AS时,它在编码列表中显示ANSI。使用这个,我可以将其编码从ANSI更改为UTF8,并且在这种情况下它不会更改任何内容/字符。但是当使用CODE时,它不起作用。将文本文件的编码从ANSI更改为UTF8,而不会影响C#中文件的任何字符!
==>第一种方法我用于实现由以下编码:
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);
==>第二替代其中我使用:
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);
}
}
}
}
==>我使用第三备选:
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();
但不幸的是,上述解决方案都没有为我工作。
这不以任何方式适用于问如问。 – 2017-12-13 11:36:27