How to read a file into a stream

M

Marc Gravell

Well, File.OpenRead(@"c:\myfile.zip") would give you a FileStream
looking at the file.

With the exception of MemoryStream, you don't really really read *into*
a stream; rather, the stream is a pipe through which you read the file
as you need it (i.e. a few thousand bytes at a time). Memory stream, on
the other hand, is a bucket.

Marc
 
J

Jon Skeet [C# MVP]

ad said:
I have a file (c:\myFile.zip) in the Server.
How can I read the file into a Stream?

Open it as a FileStream and that *is* a stream. Please give me details
on what you're really trying to do.
 
M

Marc Gravell

Trying to predict your next question, can I offer the following example
(which also servers a general demonstration of stream usage)? This code
opens the file (at inPath), obtains the first file in the zip archive,
and writes it (to outPath).

Note that this uses #ZipLib to handle zip files (not handled natively
by the CLR); note that at any point in time we are only handling 2048
bytes of data, even for a 500Mb file - so we haven't read the entire
file into memory first.

We have three streams here; we have connected two "pipes" (streams)
together, with the nifty #ZipLib code in the middle, so when you
request e.g. 2048 bytes, it reads {some} bytes from the FileStream,
decompresses it, and gives you back {some} bytes (bytesRead). We then
write this amount from the buffer to out output stream.

Code maynot be 100% - I have ported it (in notepad) from a more complex
example.

int BUFFER_LENGTH = 2048;
byte[] buffer = new byte[BUFFER_LENGTH];
using(inFile = System.IO.File.OpenRead(inPath))
using(zip = new
ICSharpCode.SharpZipLib.Zip.ZipInputStream(inFile))
using (System.IO.FileStream outFile =
System.IO.File.Create(outPath)) {
zip.GetNextEntry();
int bytesRead;
while((bytesRead = zip.Read(buffer, 0, BUFFER_LENGTH)) > 0)
{
outFile.Write(buffer, 0, bytesRead);
}
outFile.Flush();
outFile.Close();
}

Marc
 
?

=?ISO-8859-1?Q?Arne_Vajh=F8j?=

Marc said:
Note that this uses #ZipLib to handle zip files (not handled natively
by the CLR);

I use #ZipLib as well.

But as someone once pointed out to me then .NET supports
java.lang.zip in the vjslib assembly for J# !

Arne
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top