Stream Question

music7611

Active member
Joined
Jan 24, 2004
Messages
35
Hi all. I have a two streams in C#. One is one that comes from a file on the internet, the other is a file on the computer. I need a fairly quick way to copy the content on the file on the net to the file on the computer. What is the best way to do this?
 
Cant you use a stream reader (IO.StreamReader) to read the whole file at once and then a stream writer (IO.StreamWriter) to write the whole file at once?
 
I thought of that, but wont that mean if you want to download a big file, you have to keep it all in the ram?

Also, for binary files, StreamReader messes up the files. Is there a BinaryReader/Writer equivilent?
 
When I encountered a similar situation in the past, I created a method to copy the streams.

[VB]
private static long CopyData(Stream input, Stream output)
{
int amtRead = 1;
long amtCopied = 0;
byte[] buffer = new byte[8192*8];
while(amtRead > 0)
{
amtRead = input.Read(buffer, 0, buffer.Length);
amtCopied+=amtRead;
output.Write(buffer, 0, amtRead);
}
return amtCopied;
}
[/VB]
 
well... couldnt you just declare a byte array, download blocks at a time and write them?
[VB]
Dim Data() As Byte = New Byte(InsertSizeHere)
Do
Length = WebStream.Read(Data, 0, Data.Length)
FileStream.Write(Data, 0, Length)
Loop While WebStream.Length < WebStream.Position - 1
[/VB]

Didnt test this, but you can get the jist of it. And if performance becomes an issue you could look into using asynchronious methods (i.e. use BeginRead(), EndRead(), BeginWrite(), etc.)

[Edit]I guess someone beat me to giving you the same answer, and I know you were asking about C# (not that it would be hard to translate). Oh well.[/Edit]
 
Back
Top