将文本文件的编码从ANSI更改为UTF8,而不会影响C#中文件的任何字符!

vic*_*cky 1 c# windows

谁能帮我吗?我尝试了很多不同的方法,但是我没有运气得到理想的结果.我只想将现有文本[.txt]文件的编码从ANSI更改为包含ö,ü等字符的UTF8.当我通过在编辑模式下打开该文本文件然后FILE => SAVE AS手动执行此操作时,它在编码列表中显示ANSI.使用它,我能够将其编码从ANSI更改为UTF8,并且在这种情况下它不会更改任何内容/字符.但是,当使用CODE时,它无法正常工作.

==>我曾经通过以下代码实现这一目标:

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);
Run Code Online (Sandbox Code Playgroud)

==>我使用的第二种替代品:

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);

            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

==>我使用的第三种替代方案:

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();
Run Code Online (Sandbox Code Playgroud)

但不幸的是,上述解决方案都不适用于我.

Guf*_*ffa 6

ANSI的问题在于它不是特定的编码,它只是"一些8位编码的术语,它是创建它的系统的默认编码".

如果文件是在同一系统上创建的,并且默认编码没有更改,则可以使用Encoding.Default它来读取它,因此您的第一个和第三个版本可以正常工作.(您的第二个版本只是复制文件而不做任何更改.)否则您必须确切知道使用了哪种编码.

此示例使用windows-1250代码页:

File.ReadAllText(path, Encoding.GetEncoding(1250))
Run Code Online (Sandbox Code Playgroud)

有关可用编码的列表,请参阅Encoding类的文档.