FileOpenPicker - 如何读取特殊字符

FileOpenPicker - How to read special characters

我对 FileOpenPicker 有疑问。我使用特殊字符,例如ś ć ę 和我的文件 .txt 包含以下内容: "śś ćć ə ó"

这是我的代码:

var picker = new Windows.Storage.Pickers.FileOpenPicker();
picker.ViewMode = Windows.Storage.Pickers.PickerViewMode.List;
picker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.Desktop;
picker.FileTypeFilter.Add(".txt");

Windows.Storage.StorageFile file = await picker.PickSingleFileAsync();
if (file != null)
{
    using (var inputStream = await file.OpenReadAsync())
    using (var classicStream = inputStream.AsStreamForRead())
    using (var streamReader = new StreamReader(classicStream))
    {
        var something = streamReader.ReadToEnd();
    }
}

当我阅读我的文件时,我得到这样的信息:

�� �� ��

我试过更改文化、编码,但什么都没有。

这个class是怎么回事?

我非常感谢对此的任何帮助或指导。谢谢!

问题不在于class,而在于txt文件的编码。可能您已将编码设置为 ANSI,如果您尝试用您的代码读取它,它会给您奇怪的字符。要正确执行此操作,您必须定义特定的编码以及注册提供商:

var picker = new Windows.Storage.Pickers.FileOpenPicker();
picker.ViewMode = Windows.Storage.Pickers.PickerViewMode.List;
picker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.Desktop;
picker.FileTypeFilter.Add(".txt");
Windows.Storage.StorageFile file = await picker.PickSingleFileAsync();
if (file != null)
{
    // register provider - by default encoding is not supported
    Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance);
    using (var inputStream = await file.OpenReadAsync())
    using (var classicStream = inputStream.AsStreamForRead())
    using (var streamReader = new StreamReader(classicStream, Encoding.GetEncoding(1250)))
    {
        var something = streamReader.ReadToEnd();
    }
}

如果您使用 UTF-8 编码保存文件,那么您可以立即阅读它会容易得多。