如何将下载的数据写入多个文件?

vis*_*213 -3 c# networking stream

我正在尝试将下载的所有字节写入3个不同的文件,现在,我正在使用WebRequest和WebResponse对象.我确定它是正确的方法吗?我陷入了将数据写入部分文件的部分困难.无论写入什么数据,目前的目标是从同一个流中读取数据并将其写入3个不同的文件.我可以成功写入第一个文件,而不是它给出错误 - 当我尝试将流(我从response.getResponseStream()获取)分配给另一个二进制读取器时,流不可读.

我尝试过两种方法 - 一种是直接将响应流传递给不同的二进制读取器,失败了.其次,我尝试为每个二进制读取器创建separte引用,但也失败了.这是代码,如果它可以帮助: -

using (Stream strm = res.GetResponseStream())
{
    using (Stream strm1 = strm)
    {
        int i = 0;
        BinaryReader br = new BinaryReader(strm1);
        br.BaseStream.BeginRead(buffer, 0, buffer.Length, 
            new AsyncCallback(ProcessDnsInformation), br);
        Console.WriteLine("Data read {0} times", i++);
        Console.ReadKey();
        File.WriteAllBytes(@"C:\Users\Vishal Sheokand\Desktop\Vish.bin", buffer);
        br.Close();
    }

    using (Stream strm2=strm)
    {
        int i = 0;
        BinaryReader br = new BinaryReader(strm2);
        br.BaseStream.BeginRead(buffer, 0, buffer.Length, 
            new AsyncCallback(ProcessDnsInformation), br);
        Console.WriteLine("Data read {0} times", i++);
        Console.ReadKey();
        File.WriteAllBytes(@"C:\Users\Vishal Sheokand\Desktop\Vish1.bin", buffer);
        br.Close();
    }

    using (Stream strm3 = strm)
    {
        int i = 0;
        BinaryReader br = new BinaryReader(strm3);
        br.BaseStream.BeginRead(buffer, 0, buffer.Length, 
            new AsyncCallback(ProcessDnsInformation), br);
        Console.WriteLine("Data read {0} times", i++);
        File.WriteAllBytes(@"C:\Users\Vishal Sheokand\Desktop\Vish2.bin", buffer);
        br.Close();
    }
}
Run Code Online (Sandbox Code Playgroud)

我正在学习C#,请忽略一些(或全部)愚蠢的编码.

Jon*_*eet 5

你至少有两个问题.首先,看看这个:

using (Stream strm = res.GetResponseStream())
{
    using (Stream strm1 = strm)
    {
        ...
    }
Run Code Online (Sandbox Code Playgroud)

一旦退出内部块,流将被丢弃 - 因此您无法在下一个块中读取它.

其次,你正在调用BeginRead哪个将开始读取数据 - 但是当你决定写入所有数据时,你已经完全解除了回调的时间.我强烈建议您首先使用同步IO来完成所有这些工作,然后在适当的情况下转移到异步IO.