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.

我该怎么办?

4

3 回答 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);
        }

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

于 2013-08-13T11:39:54.943 回答
5

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

dataReader.ReadBytes(stream);
string text = Convert.ToBase64String(stream);
于 2013-08-13T10:37:30.887 回答
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;
        }
于 2019-05-16T19:20:10.570 回答