Wednesday 15 May 2013

CodeSnippet - Copy stream

/// <summary>
/// Copies the contents of input to output. Doesn't close either stream.
/// </summary>
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);
    }    
}
 
 
http://stackoverflow.com/questions/411592/how-do-i-save-a-stream-to-a-file
 
 

public void DoFileDeletingLogic(){         
   string file = _dataPath + "\\file.txt";
            string fileTemp = _dataPath + "\\fileTemp.txt";
            
            if (!File.Exists(file))
            {
                throw new Exception("File does not exists");
            }

            FileStream fileStream = File.OpenRead(file);
            
   // copy file into new file
   using (Stream newfile = File.OpenWrite(fileTemp))
            {
                CopyStream(fileStream, newfile);
            }
            // and dispose of the stream, as now its locked for access.
   fileStream.Dispose();

            // do your logic here that deletes file
   
   
            if (File.Exists(file))
            {
                throw new Exception("File should be deleted");
            }
            else
            {
                // replace existing file
                File.Move(fileTemp, file);
            }
        }

        /// <summary>
        /// Copies the contents of input to output. Doesn't close either stream.
        /// </summary>
        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);
            }
        }

No comments:

Post a Comment