I am downloading a xml file from the internet and save it in isolated storage. If I try to read it I get an error:
Data at the root level is invalid. Line 1, position 1.
string tempUrl = "http://xxxxx.myfile.xml"; // changed
WebClient client = new WebClient();
client.OpenReadAsync(new Uri(tempUrl));
client.OpenReadCompleted += new OpenReadCompletedEventHandler(delegate(object sender, OpenReadCompletedEventArgs e) {
StreamWriter writer = new StreamWriter(new IsolatedStorageFileStream("myfile.xml", FileMode.Create, FileAccess.Write, myIsolatedStorage));
writer.WriteLine(e.Result);
writer.Close();
});
This is how I download and save the file...
And I try to read it like that:
IsolatedStorageFileStream fileStream = myIsolatedStorage.OpenFile("myfile.xml", FileMode.Open, FileAccess.Read);
XDocument xmlDoc = XDocument.Load(fileStream);
This is where I get the error...
I have no problem reading the same file without downloading and saving it to isolated storage... so there must be the fault.
This:
writer.WriteLine(e.Result);
doesn't do what you think it does. It's just calling ToString()
on a Stream
, and writing the result to a file.
I suggest you avoid using a StreamWriter
completely, and simply copy from e.Result
straight to the IsolatedStorageFileStream
:
using (var output = new IsolatedStorageFileStream("myfile.xml", FileMode.Create,
FileAccess.Write, myIsolatedStorage))
{
CopyStream(e.Result, output);
}
where CopyStream
would be a method to just copy the data, eg
public static void CopyStream(Stream input, Stream output)
{
byte[] buffer = new byte[8 * 1024];
int read;
while((read = input.Read (buffer, 0, buffer.Length)) > 0)
{
output.Write (buffer, 0, read);
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.