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

徘徊边缘 提交于 2019-11-30 17:58:52

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?

Try this instead of string text = dataReader.ReadString(numbytes):

dataReader.ReadBytes(stream);
string text = Convert.ToBase64String(stream);

If, like me, this was the top result when search for the same error regarding UWP, see the below:

The code I had which was throwing the error (no mapping for the unicode character exists..):

  var storageFile = await Windows.Storage.AccessCache.StorageApplicationPermissions.FutureAccessList.GetFileAsync(fileToken);
        using (var stream = await storageFile.OpenAsync(FileAccessMode.Read))
        {
            using (var dataReader = new DataReader(stream))
            {
                await dataReader.LoadAsync((uint)stream.Size);
                var json = dataReader.ReadString((uint)stream.Size);
                return JsonConvert.DeserializeObject<T>(json);
            }
        }

What I changed it to so that it works correctly

     var storageFile = await Windows.Storage.AccessCache.StorageApplicationPermissions.FutureAccessList.GetFileAsync(fileToken);
        using (var stream = await storageFile.OpenAsync(FileAccessMode.Read))
        {
            T data = default(T);
            using (StreamReader astream = new StreamReader(stream.AsStreamForRead()))
            using (JsonTextReader reader = new JsonTextReader(astream))
            {
                JsonSerializer serializer = new JsonSerializer();
                data = (T)serializer.Deserialize(reader, typeof(T));
            }
            return data;
        }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!