2

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!

Romasz
  • 29,662
  • 13
  • 79
  • 154
Kiro
  • 43
  • 1
  • 5
  • Problem might be in your file, first what encoding is your text file? Then open the StreamReader with the same encoding which you did not specify explicitly. (I recommend to use UTF8 encoding) – kurakura88 Jan 23 '17 at 04:07

1 Answers1

0

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

Romasz
  • 29,662
  • 13
  • 79
  • 154