I was able to reproduce the error even with reading a local file. The reason for the error is that the DataReader puts some extra Bytes before the content. You don't see them in the debugger, but when putting the read content in Notepad++ for example, you get an extra question mark:
?<?xml version="1.0" encoding="utf-8"?>
As I suspected the extra bytes were the Byte Order Mark (BOM) bytes (0xEF 0xBB 0xBF (239 187 191)).
I tried to set the encoding for the DataReader explicitly to UTF8 but that did not change anything. Seems to be a bug in the DataReader. B.T.W.. You would get the same error when reading the bytes from the DataReader and try to convert them using Encoding.UTF8.GetString. Even that method does not recognize the BOM.
Okay. Two workarounds:
1) Use FileIO.ReadTextAsync:
string content = await FileIO.ReadTextAsync(file);
2) Use a StreamReader:
using (var stream = await file.OpenReadAsync())
{
using (var readStream = stream.AsStreamForRead())
{
using (StreamReader streamReader = new StreamReader(readStream))
{
string content = streamReader.ReadToEnd();
XmlDocument doc = new XmlDocument();
doc.LoadXml(content);
}
}
}
Update:
The method ReadFileInfo would look like this to avoid the BOM problem. Note that AsStreamForRead is an extension method available in System.IO (put using System.IO; in your code).
private async Task ReadFileInfo(string folderId)
{
LiveOperationResult operationResultFile =
await client.GetAsync(folderId + "/files");
dynamic resultFile = operationResultFile.Result;
IDictionary<string, object> fileData = (IDictionary<string, object>)resultFile;
List<object> files = (List<object>)fileData["data"];
foreach (object item in files)
{
IDictionary<string, object> file = (IDictionary<string, object>)item;
if (file["name"].ToString() == "ocha.txt")
{
LiveDownloadOperationResult DLFile =
await client.BackgroundDownloadAsync(file["source"].ToString());
using (var stream = await DLFile.GetRandomAccessStreamAsync())
{
using (var readStream = stream.AsStreamForRead())
{
using (StreamReader streamReader = new StreamReader(readStream))
{
string content = streamReader.ReadToEnd();
XmlDocument doc = new XmlDocument();
doc.LoadXml(content);
VM.importVehicles(content);
break;
}
}
}
}
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…