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

时间:2013-08-13 10:23:47

标签: file-io windows-8 windows-runtime datareader

我正在尝试在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.

我如何得到这个?

3 个答案:

答案 0 :(得分: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);
        }

有人可以详细说明,为什么我的初步方法不起作用?

答案 1 :(得分:5)

尝试使用此代替string text = dataReader.ReadString(numbytes)

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

答案 2 :(得分: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;
        }