WinRT:目标多字节代码页中不存在Unicode字符的映射。

13

我正在尝试在我的Windows 8商店应用程序中读取文件。以下是我用来实现此目的的代码片段:

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

然而,在该行代码处抛出了一个异常:

string text = dataReader.ReadString(numbytes);

异常信息:

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

我该怎么度过这个难关?


1
不寻常的是,我认为WinRT仍然处理多字节编码。但它指向一个未正确编码的文本文件。 - Hans Passant
3个回答

19

我成功地使用与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);
        }

有人能详细解释一下,为什么我的初始方法不起作用吗?


当字符为中文时,它会将记事本保存的编码ASCII读取为“?”。我尝试使用Encoding.ASCII.GetString。可以帮忙吗? - lindexi
@lindexi ASCII 编码不支持中文字符。更多信息请参见这里 - Jarek Mazur

5

尝试使用以下代码替换string text = dataReader.ReadString(numbytes):

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

0

如果像我一样,当搜索与 UWP 相关的相同错误时,这是排名第一的结果,请参见下面:

引发此错误的代码(不存在 Unicode 字符的映射..):

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

我所做的更改以使其正常工作

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接