简体   繁体   English

FileOpenPicker-如何读取特殊字符

[英]FileOpenPicker - How to read special characters

I have problem with FileOpenPicker. 我对FileOpenPicker有问题。 I use special characters eg ś ć ę and my file .txt has content: "śś ćć ę ó" 我使用特殊字符(例如śćę)和我的文件.txt包含内容:“śśććęó”

It is my code: 这是我的代码:

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

And when I read my file I get something like this: 当我读取文件时,会得到如下信息:

在此处输入图片说明

I tried change culture, encoding and nothing. 我尝试过更改文化,编码,但一无所获。

How is the problem with this class? 这堂课怎么了?

I really appreciate any help or guidance on this. 我真的很感谢任何帮助或指导。 Thanks! 谢谢!

The problem is not with the class, but with the encoding of txt file. 问题不在于类,而在于txt文件的编码。 Probably you have set encoding as ANSI , which will give you strange characters if you try to read it with your code. 可能您已将编码设置为ANSI ,如果您尝试与代码一起阅读,则会给您带来奇怪的字符。 To do it properly you will have to define the certain encoding along with registering provider: 要正确执行此操作,您将必须定义某些编码以及注册提供程序:

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

Much easier it would be if you had saved your file with UTF-8 encoding, then you could have read it just right away. 如果您使用UTF-8编码保存文件,则容易得多,那么您可以立即读取它。

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM