【问题标题】:How to read a text file with other encoding than UFT8 or UTF16 in WinRT?如何在 WinRT 中读取除 UFT8 或 UTF16 之外的其他编码的文本文件?
【发布时间】:2013-06-20 17:54:25
【问题描述】:

如果我使用 FileIO.ReadTextAsync、ReadLinesAsync 或 DataReader 读取文本文件,我只能指定 UnicodeEncoding 枚举的成员进行编码。由于某种原因,这仅包括 Utf8、Utf16BE 和 Utf16LE。那么如何读取具有其他编码(如 Windows-1252 甚至常规 Unicode(所有字符 2 字节))的文本文件?

如果 Windows 应用商店应用程序与桌面应用程序共享文本文件或从 Internet 读取文本文件,这可能很重要。

【问题讨论】:

  • 这不是出于“某种原因”,这是对使用错误编码读取文本文件的永无止境的损失的硬性停止。 Utf-16 是“常规 Unicode”,使用 2 个字节。您可以通过读取二进制数据并使用 Encoding 类转换文本来自己旋转它。
  • 谢谢汉斯。我不知道 Encoding.Unicode 实际上是 UTF-16 LE(实际上使用 2 或 4 个字节)。我为“硬停”假设了相同的原因,但我想确定。这确实有道理。使用 BOM 读取 UTF-8 或 UTF-16 文件总是成功,即使我传递了错误的编码(当存在 BOM 时显然会被忽略)。好吧,在读取没有 BOM 的 UTF 编码文本文件时,我们仍然可能会遇到问题(我检查过)。但这样的文件将非常罕见。感谢 Encoding.GetString 的提示。我忘记了 :-) 会将其标记为答案。

标签: windows-runtime winrt-xaml windows-store-apps


【解决方案1】:

汉斯的评论实际上回答了我的问题。 Windows-1252 示例:

string filePath = ...
StorageFile file = await StorageFile.GetFileFromPathAsync(filePath);
IBuffer buffer = await FileIO.ReadBufferAsync(file);
byte[] fileData = buffer.ToArray();
Encoding encoding = Encoding.GetEncoding("Windows-1252");
string text = encoding.GetString(fileData, 0, fileData.Length);

【讨论】:

    【解决方案2】:

    @JürgenBayer buffer.ToArray() 不适合我。

    所以,不要写:

    string text = await FileIO.ReadTextAsync(file);
    

    我写道:

    IBuffer buffer = await FileIO.ReadBufferAsync(file);
    byte[] fileData;
    CryptographicBuffer.CopyToByteArray(buffer, out fileData);
    Encoding encoding = Encoding.GetEncoding("Windows-1252");
    string text = encoding.GetString(fileData, 0, fileData.Length);
    

    【讨论】:

    • ToArray 是 WindowsRuntimeBufferExtensions 类的扩展方法,如果包括命名空间 System.Runtime.InteropServices.WindowsRuntime 则可用。但是你的代码看起来也不错:-)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-05
    • 2022-08-09
    • 2021-09-15
    • 2019-11-14
    • 2012-11-17
    相关资源
    最近更新 更多