read/write one to the other
I'm trying to find an efficient way of reading a stream of data directly writing to a filestream. Is there a way?
I don't want to read everything into byte[] then write the byte[] to the filestream, I want to avoid the reading to byte[] as you wouldnt know how big this file would be. (and its not quite a file copy)
any ideas?
Re: read/write one to the other
What sort of stream is the data coming from? The MemoryStream class has a WriteTo method that does exactly what you want, but I don't think other stream types do, or at least the FileStream certainly doesn't.
Having said that, using a buffer is no issue. You don't have to read the entire stream in one go. Make your buffer a specific size then read the the input and write the output in blocks that size. The Read method will tell you exactly how many bytes were read so you'll always know exactly how many bytes to write, e.g.
Code:
// Use a 4K buffer.
const int bufSize = 4096;
byte[] buffer = new byte[bufSize];
int bytesRead = strm1.Read(buffer, 0, bufSize);
do
{
strm2.Write(buffer, 0, bytesRead);
bytesRead = strm1.Read(buffer, 0, bufSize);
} while (bytesRead > 0);
Re: read/write one to the other
yes I was thinking about doing that (your last request) but i dunno. Basically its coming from an embedded resource, and would be nice to extract it to a file on disk.
Re: read/write one to the other
Edited my previous post to include a code example.
Re: read/write one to the other
An embedded resource as in Properties.Resources? If so then the property itself is type byte[], so there's no need for you to worry about the size, e.g.
Code:
byte[] fileResource = Properties.Resources.FileName;
myFileStream.Write(fileResource, 0, fileResource.Length);