I am trying to write all bytes downloaded into 3 different files, Now, I am using WebRequest and WebResponse Objects. I am sure its the correct way to go?
I got stuck in part of writing data to files in parts.No matter what data is written,objective right now is to read data from same stream and write it to 3 different files.
I can write to the first file successfully, than it gives error–stream is not readable when I try to assign the stream(which I got from response.getResponseStream()) to another binaryreader.
I have tried it two ways-one is to directly pass responsestream to different binaryreaders,failed.
Secondly I tried to create separte references for each binaryreader,that failed too.
Here is the code if it can help:-
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();
}
}
I am learning C#, please ignore some(or all of) stupid coding.
You have at least two problems. First, look at this:
As soon as you’ve exited the inner block, the stream will be disposed – so you can’t read from it in the next block.
Secondly, you’re calling
BeginReadwhich is going to start reading data – but then you’ve completely decoupled the timing of the callback from when you decide to write all the data. I would strongly advise you to get all this working with synchronous IO first, then move onto asynchronous IO if appropriate.