1

Is there an equivalent of

System.Text.Encoding.UTF8.GetString(fileContent) 

in WinJS (Windows 8 Store App written in javascript/HTML)?

EDIT. fileContent is a byte array.

Jarek Mazur
  • 2,052
  • 1
  • 25
  • 41

2 Answers2

2

There is no strict equivalent of System.Text.Encoding.UTF8.GetString in WinJS, but you can try implement file reading to string as follows:

file.openReadAsync().done(function (stream) {
   var blob = MSApp.createBlobFromRandomAccessStream(file.contentType, stream);
   var reader = new FileReader();

   reader.onload = function(event) {
      var fileAsText = event.target.result;
   };

   reader.readAsText(blob, 'UTF-8');
});

In most cases (file upload via XHR, displaying file) you don't need to have file contents as text, so just use Blob then.

roryok
  • 9,325
  • 17
  • 71
  • 138
T W
  • 6,267
  • 2
  • 26
  • 33
  • Ok works great, but you have one small error in your code: you forgot to add parenthesis after openReadAsync (it should be file.openReadAsync().done(...)) – Jarek Mazur Aug 14 '13 at 08:10
  • One more question - do you happen to know how to handle unicode symbols (file I am trying to read contains polish letters) – Jarek Mazur Aug 14 '13 at 08:11
  • thanks, that was the only way i could read a text file from Excel with dutch characters (saved as encoding LATIN1) – fnicollet Apr 12 '16 at 10:19
0

CryptographicBuffer.convertBinaryToString can be used for this.

var crypt = Windows.Security.Cryptography;
var bytes; // = new Uint8Array(100);
// TODO - set bytes variable with uint8array
var buffer = crypt.CryptographicBuffer.createFromByteArray(bytes);
var text = crypt.CryptographicBuffer.convertBinaryToString(
    crypt.BinaryStringEncoding.utf8, buffer);
Sushil
  • 5,265
  • 2
  • 17
  • 15
  • Using your approach I get runtime exception: "No mapping for the Unicode character exists in the target multi-byte code page." – Jarek Mazur Aug 14 '13 at 08:17