Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

saving a file (from stream) to disk using c# [duplicate]

Tags:

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...

like image 791
Haroon Avatar asked Feb 15 '11 11:02

Haroon


2 Answers

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);
}
like image 67
rotman Avatar answered Sep 19 '22 16:09

rotman


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();
like image 23
Shekhar_Pro Avatar answered Sep 20 '22 16:09

Shekhar_Pro