【问题标题】:c# change file encoding without loading all the file in memoryc#更改文件编码而不加载内存中的所有文件
【发布时间】:2016-03-11 06:49:03
【问题描述】:

我需要更改文件的编码。我使用的方法将所有文件加载到内存中:

string DestinationString = Encoding.ASCII.GetString(Encoding.ASCII.GetBytes(File.ReadAllText(FileName)));
File.WriteAllText(FileName, DestinationString, new System.Text.ASCIIEncoding());

这适用于较小的文件(如果我想将文件的编码更改为ASCII),但对于大于 2 GB 的文件就不行了。如何在不将所有文件内容加载到内存的情况下更改编码?

【问题讨论】:

    标签: c# file-encodings


    【解决方案1】:

    您无法通过写入 same 文件来做到这一点 - 但您可以轻松地写入 不同 文件,只需在一次编码中的时间并以目标编码写入每个块。

    public void RewriteFile(string source, Encoding sourceEncoding,
                            string destination, Encoding destinationEncoding)
    {
        using (var reader = File.OpenText(source, sourceEncoding))
        {
            using (var writer = File.CreateText(destination, destinationEncoding))
            {
                char[] buffer = new char[16384];
                int charsRead;
                while ((charsRead = reader.Read(buffer, 0, buffer.Length)) > 0)
                {
                    writer.Write(buffer, 0, charsRead);
                }
            }
        }
    }
    

    当然,您总是可以通过重命名获得原始文件名。

    【讨论】:

    • 旁注:很明显,可以将编码 更改为 ASCII,因为它是固定宽度编码,并且不需要比任何其他编码更多的字节(是否值得做是另一回事)
    • @AlexeiLevenkov:有可能,但这会很棘手,因为文件最终可能会缩小。我肯定会鼓励我在这里建议的方法。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-10-31
    • 2020-06-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多