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

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

==> 我使用的第二个替代方案:

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

但不幸的是,上述解决方案都不适合我。

最佳答案

ANSI 的问题在于它不是一种特定的编码,它只是“某些 8 位编码,这是创建它的系统的默认编码”的术语。

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

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

File.ReadAllText(path, Encoding.GetEncoding(1250))

请参阅 Encoding class 的文档获取可用编码列表。

关于c# - 将文本文件的编码从 ANSI 更改为 UTF8,而不影响 C# 中文件的任何字符!,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10296655/

相关文章:

c# - 在 Visual Studio : Test-case objects missing 中运行单元测试时出错

c# - 影响 EF 代码中的外键列命名(CTP5)

windows - cmd 以某种方式将中文文本作为输出

java - 在 Java 中检测 CapsLock

c# - DidReceiveRemoteNotification 未在后台调用 - Xamarin iOS - 推送通知

c# - 如何确定调用方法和类名?

c# - 启用写入映射到内存的文件

windows - 以 ubuntu 作为基础镜像的 Docker 应用程序如何在 Windows 上运行?

c# - 如何防止截断事件日志中的服务异常

python - 如何使用 pyinstaller 将包转换为 exe?