【问题标题】:Cannot read text file in Shift JIS cp392 encoding无法读取 Shift JIS cp392 编码的文本文件
【发布时间】:2013-07-23 17:10:30
【问题描述】:

在 Windows Store 应用程序中读取 Shift JIS cp392 编码的文本文件时遇到问题。 我使用此代码读取文本文件:

var streamOpenedFile = await file.OpenAsync(FileAccessMode.Read);

using (var inputOpenedFile = streamOpenedFile.GetInputStreamAt(0))
{
    using (StreamReader reader = new StreamReader(inputOpenedFile.AsStreamForRead(), Encoding.UTF8))
    {
        fileContent = await reader.ReadToEndAsync();
    }
}

但是我在fileContent中收到的字符串只是一个奇怪的字符,当我用记事本打开它时看起来不像字符串。 谁能帮我解决这个问题? 非常感谢。

【问题讨论】:

    标签: c# windows windows-8 windows-runtime


    【解决方案1】:

    您似乎已将输入流标记为 UTF-8,这意味着输入流将被解释为 UTF-8 而不是 Shift JIS。如果您希望将其解释为 Shift JIS,则需要更改 reader 的编码。

    var streamOpenedFile = await file.OpenAsync(FileAccessMode.Read);
    
    using (var inputOpenedFile = streamOpenedFile.GetInputStreamAt(0))
    {
        using (StreamReader reader =
              new StreamReader(
                 inputOpenedFile.AsStreamForRead(),
                 Encoding.GetEncoding(932))
        {
            fileContent = await reader.ReadToEndAsync();
        }
    }
    

    【讨论】:

    • 感谢您的回答,但我发现了异常:'392' 不是受支持的编码名称。我尝试将“Shift_JIS”传递给 GetEncoding 函数并看到它也能正常工作。现在我明白怎么读了,但我还在考虑是否可以知道文本文件的编码?
    • 392 不是 Shift JIS 代码页 932 是......我没有检查的错误。遗憾的是,除了暴力破解之外,没有其他方法可以检查编码,除非文档格式类似于 HTML,它指定了检测文档编码的一系列步骤。如果可能,更好的选择是始终使用 UTF-8 保存文本文件。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-24
    • 2017-03-12
    相关资源
    最近更新 更多