Mugen
Mugen

Reputation: 9095

FileStream move instead of copy

I'm trying to concatanate two very big files (potentially, a few GB). I have no need to preserve their original content, I'm only interested in the result.

I've seen that the most efficient way to append one file to the other is using FileStream.CopyTo().

However, as you all know a move operation is much cheaper than a copy. If I wanted to move the files around the file system, I would use File.Move and not File.Copy.

Is there any equivalent to file streams? Or any other way surrounding the file? I can also use non-C# methods.

Upvotes: 0

Views: 2270

Answers (2)

rory.ap
rory.ap

Reputation: 35318

"Files" in a file system are much higher-level concepts than streams. A lot of stuff is happening "under the hood" that you don't realize to optimize performance, etc., when you perform file operations in the file system.

File streams on the other hand, are a programming concept that give you the ability to work with files in a much-more-granular way. You can't simply "move" a file stream to another file stream; "moving" is an illusion created by the operating system, which, as Luaan pointed out, is simply the OS just changing the pointer to the file rather than picking up the file and moving it to somewhere else on the drive.

If you think about it, how could that even really work? A file is a series of ones and zeroes stored in some static medium (e.g. disk drive). You can't simultaneously wipe out the ones and zeros where the file resides and write them to the new location. You would have to first copy the ones and zeros to the new location then delete them at their old location. If the OS really did it this way (instead of the aforementioned pointer method), it would abstract the operation out so it seemed to the user that the file was just being picked up and moved somewhere else all in one step.

Upvotes: 2

Luaan
Luaan

Reputation: 63772

No.

The file-system move operation only changes the path to a file - that's what makes it fast. There's no analogue when you're trying to merge two files, no matter how.

The best you can do is append the contents of the second file to the first file - at least you'll avoid copying the first file. That's what FileStream.CopyTo does (don't forget to seek to the end of the first file first).

Upvotes: 3

Related Questions