Search code examples
c#uwpfileopenpicker

FileOpenPicker - How to read special characters


I have problem with FileOpenPicker. I use special characters e.g. ś ć ę and my file .txt has content: "śś ćć ę ó"

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:

enter image description here

�� �� �

I tried change culture, encoding and nothing.

How is the problem with this class?

I really appreciate any help or guidance on this. Thanks!


Solution

  • The problem is not with the class, but with the encoding of txt file. Probably you have set encoding as ANSI, which will give you strange characters if you try to read it with your code. 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.

    enter image description here