Possible Duplicate:
How do I save a stream to a file?
I have got a stream object which may be an image or file (msword, pdf), I have decided to handle both types very differently, as I may want to optimize/ compress / resize / produce thumbnails etc. I call a specific method to save an image to disk, the code:
var file = StreamObject;
//if content-type == jpeg, png, bmp do...
Image _image = Image.FromStream(file);
_image.Save(path);
//if pdf, word do...
How do I actually save word and pdfs?
//multimedia/ video?
I have looked (not hard enough probably) but I could not find it anywhere...
If you are using .NET 4.0 or newer you can use this method:
public static void CopyStream(Stream input, Stream output)
{
input.CopyTo(output);
}
If not, use this one:
public static void CopyStream(Stream input, Stream output)
{
byte[] buffer = new byte[8 * 1024];
int len;
while ( (len = input.Read(buffer, 0, buffer.Length)) > 0)
{
output.Write(buffer, 0, len);
}
}
And here how to use it:
using (FileStream output = File.OpenWrite(path))
{
CopyStream(input, output);
}
For file Type you can rely on FileExtentions and for writing it to disk you can use BinaryWriter. or a FileStream.
Example (Assuming you already have a stream):
FileStream fileStream = File.Create(fileFullPath, (int)stream.Length);
// Initialize the bytes array with the stream length and then fill it with data
byte[] bytesInStream = new byte[stream.Length];
stream.Read(bytesInStream, 0, bytesInStream.Length);
// Use write method to write to the file specified above
fileStream.Write(bytesInStream, 0, bytesInStream.Length);
//Close the filestream
fileStream.Close();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With