根级的数据无效。1号线,位置1

时间:2021-05-12 18:31:59

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:

我正在从因特网上下载一个xml文件,并将它保存在独立的存储中。如果我试着读它,我会得到一个错误:

Data at the root level is invalid. Line 1, position 1.

根级的数据无效。1号线,位置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.

如果不下载并保存到独立的存储中,我可以毫无问题地阅读相同的文件。所以一定有错。

1 个解决方案

#1


8  

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.

不像你想的那样。它只是在流上调用ToString(),并将结果写入文件。

I suggest you avoid using a StreamWriter completely, and simply copy from e.Result straight to the IsolatedStorageFileStream:

我建议您完全避免使用StreamWriter,并简单地从e复制。结果直接到隔离存储文件流:

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, e.g.

CopyStream是一种只复制数据的方法,例如。

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);
    }
}

#1


8  

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.

不像你想的那样。它只是在流上调用ToString(),并将结果写入文件。

I suggest you avoid using a StreamWriter completely, and simply copy from e.Result straight to the IsolatedStorageFileStream:

我建议您完全避免使用StreamWriter,并简单地从e复制。结果直接到隔离存储文件流:

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, e.g.

CopyStream是一种只复制数据的方法,例如。

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);
    }
}