Search code examples
c#filestream

writing a large stream to a file in C#.Net 64K by 64K


Please suggest me a good method that can be used to write a stream into a file.

I just need a simple c# function that can take a stream as input and do the job.. I need to do this for very large files ie files > 4GB.

Can this be done better using linq,extension methods etc?

Please provide me a good utility function that can also return the progress in percentage through yield.

Edit: I know about looping through a byte[] and writing it to a file. I've tried File.WriteAllBytes method. But,I'm just looking for a very nice way of doing it using linq,yield and extension methods.


Solution

  • Edit: Here is a utility function that should do the trick:

    Update: Changed second parameter to file name

        public delegate void ProgressCallback(long position, long total);
        public void Copy(Stream inputStream, string outputFile, ProgressCallback progressCallback)
        {
            using (var outputStream = File.OpenWrite(outputFile))
            {
                const int bufferSize = 4096;
                while (inputStream.Position < inputStream.Length)
                {
                    byte[] data = new byte[bufferSize];
                    int amountRead = inputStream.Read(data, 0, bufferSize);
                    outputStream.Write(data, 0, amountRead);
    
                    if (progressCallback != null)
                        progressCallback(inputStream.Position, inputStream.Length);
                }
                outputStream.Flush();
            }
        }