Tuesday, September 25, 2012

WinRT ArgumentOutOfRangeException "No mapping for the Unicode character exists in the target multi-byte code page" from FileIO.ReadTextAsync()

Problem

The following code to read the text contents of a file in WinRT thru an exception on some txt files and not on others.

var localFolder = Windows.ApplicationModel.Package.Current.InstalledLocation;
var file = await localFolder.GetFileAsync("Sample.txt");
var stringContent = await Windows.Storage.FileIO.ReadTextAsync(file);
An exception of type 'System.ArgumentOutOfRangeException' occurred in mscorlib.dll but was not handled in user code

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

Additional information: No mapping for the Unicode character exists in the target multi-byte code page. (Exception from HRESULT: 0x80070459)

If there is a handler for this exception, the program may be safely continued.

Solution 1 - Remove all the problem characters

The following line in the txt file was causing the issue:

Rangitoto ki te Tonga/D’Urville Island

Changing the to a ' resolved the issue.

In another text file I also needed to change a to -.

Solution 2

Change the file encoding using Visual Studio. When I opened the file it had the encoding: "Western European (Windows) - Codepage 1252"

  1. Open the file in Visual Studio
  2. File > Advanced Save Options... >
  3. Change the encoding to "Unicode (UTF-8 with signature) - Codepage 65001"
  4. Save the file