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...
For the filestream:
//Check if the directory exists
if (!System.IO.Directory.Exists(@"C:\yourDirectory"))
{
System.IO.Directory.CreateDirectory(@"C:\yourDirectory");
}
//Write the file
using (System.IO.StreamWriter outfile = new System.IO.StreamWriter(@"C:\yourDirectory\yourFile.txt"))
{
outfile.Write(yourFileAsString);
}
if the data is already valid and already contains a pdf, word or image, then you could use a StreamWriter and save it.
I have to quote Jon (the master of c#) Skeet:
Well, the easiest way would be to open a file stream and then use:
byte[] data = memoryStream.ToArray(); fileStream.Write(data, 0, data.Length);
That's relatively inefficient though, as it involves copying the buffer. It's fine for small streams, but for huge amounts of data you should consider using:
fileStream.Write(memoryStream.GetBuffer(), 0, memoryStream.Position);
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);
}
Just do it with a simple filestream.
var sr1 = new FileStream(FilePath, FileMode.Create);
sr1.Write(_UploadFile.File, 0, _UploadFile.File.Length);
sr1.Close();
sr1.Dispose();
_UploadFile.File is a byte[], and in the FilePath you get to specify the file extention.
Source: Stackoverflow.com