Search code examples
file-iowindows-8windows-runtimedatareader

WinRT No mapping for the Unicode character exists in the target multi-byte code page


I am trying to read a file in my Windows 8 Store App. Here is a fragment of code I use to achieve this:

        if(file != null)
        {
            var stream = await file.OpenAsync(FileAccessMode.Read);
            var size = stream.Size;
            using(var inputStream = stream.GetInputStreamAt(0))
            {
                DataReader dataReader = new DataReader(inputStream);
                uint numbytes = await dataReader.LoadAsync((uint)size);
                string text = dataReader.ReadString(numbytes);
            }
        }

However, an exeption is thrown at line:

string text = dataReader.ReadString(numbytes);

Exeption message:

No mapping for the Unicode character exists in the target multi-byte code page.

How do I get by this?


Solution

  • I managed to read file correctly using similar approach to suggested by duDE:

            if(file != null)
            {
                IBuffer buffer = await FileIO.ReadBufferAsync(file);
                DataReader reader = DataReader.FromBuffer(buffer);
                byte[] fileContent = new byte[reader.UnconsumedBufferLength];
                reader.ReadBytes(fileContent);
                string text = Encoding.UTF8.GetString(fileContent, 0, fileContent.Length);
            }
    

    Can somebody please elaborate, why my initial approach didn't work?