Instead of trying to bank on the collection of memory or the GC trying to free memory. You should instead be using streams instead of large byte arrays of data. This is what streams are built for.
You can use the CopyTo method on the stream size if your application is .NET 4.5. Else you can write the chunking code manually. You can find an example in How to use Stream.CopyTo on .NET Framework 3.5?
You should be trying to do something like this:
int blockSize = 8192; // The size of the array used to chunk, default is 4096
using(var fileStream = File.Open("C:\\path\\to\\destination.file")
using(var usbStream = session.OpenFileStream(InFile)) {
usbStream.CopyTo(fileStream, blockSize);
}
This way your application will use the blockSize
(in bytes) to copy data and never more.
This would require that the session
object from your above example supports streaming I/O. Else, if you have written the session
class re-work it to support streaming by returning a Stream
instead of a byte[]
.
You will never have to worry about the size of the file you are copying crashing your program. You will be able to support whatever the underlying file system(s) supports.