我正在开发一个应该下载和处理大型XML文件的.Net应用程序。下载这些XML需要一段时间,因此我们需要能够取消它。这是我负责“可取消”下载的代码:
bool canceled = false;
using (WebResponse response = request.GetResponse())
using (Stream responseStream = response.GetResponseStream())
{
int Lenght = 2048;
Byte[] buffer = new byte[Lenght];
List<Byte> bytes = new List<byte>();
int bytesRead = responseStream.Read(buffer, 0, Lenght);
while (bytesRead > 0)
{
bytes.AddRange(buffer);
bytesRead = responseStream.Read(buffer, 0, Lenght);
// BackgroundWorker instance
if (!worker.CancellationPending) continue; // break if cancelation is pending
canceled = true;
break;
}
if (canceled) break;
xmlAsString = System.Text.Encoding.Default.GetString(bytes.ToArray());
然而由于某种原因,最后一个缓冲包(在这种情况下为2048字节)在某处“丢失”,之后当我尝试解析 xmlAsString 时出现异常。
以下是预期XML的示例
<experiments>
<experiment>
<Lots of XML tags/>
<organism>Homo sapiens</organism>
</experiment>
</experiments>
下载后的xmlAsString看起来像这样
<experiments>
<experiment>
<Lots of XML tags/>
<organism>Homo sap
但是如果我像这样逐字节地读取流
responseStream.ReadByte();
它工作正常,但下载速度慢慢下降。任何指导都可能导致这一点值得高度赞赏。感谢。