Google
 

Wednesday, June 13, 2007

Write stream to a new file in C#?


///  <summary>
/// Write a stream to the file and if the file exists, it will be over written.
/// Assume the file full path has the right format
///  </summary>
///  <param name="sourceStream"> the stream to write</param>
/// <param name="fileFullPath">  the full path of the target file</param>
public  static void WriteStreamToFile(Stream sourceStream,  string fileFullPath)
{
    
if (sourceStream  == null ||  fileFullPath == null  || fileFullPath ==  string.Empty)
        
throw new  ArgumentNullException();
    
// Create file by the file full path
    FileStream fileStream = File.Create(fileFullPath);

    
//  copy stream to byte array
    byte[] buffer  = new byte [sourceStream.Length];
    sourceStream.Read(buffer, 
0, buffer.Length);

    
// write byte array to tart file stream
    fileStream.Write(buffer,  0, buffer.Length);

    
// close file stream to save file stream to physical file
    fileStream.Close();
}


--
Happy day, happy life!

No comments: