Paul
Paul

Reputation: 347

c# Why is last byte of copied file different?

I am writing a program to read and write a specific binary file format. I believe I have it 95% working. I am running into a a strange problem.

In the screenshot I am showing a program I wrote that compares two files byte by byte. The very last byte should be 0 but is FFFFFFF.

Using a binary viewer I can see no difference in the files. They appear to be identical. Also, windows tells me the size of the files is different but the size on disk is the same.

Can someone help me understand what is going on? alt text

The original is on the left and my copy is on the right.

Upvotes: 1

Views: 439

Answers (2)

Phil Wright
Phil Wright

Reputation: 22906

Size on disk vs Size

First of all you should note that the Size on disk is almost always different from the Size value because the Size on disk value reflects the allocated drive storage but the Size reflects the actual length of the file.

A disk drive splits its space into blocks of the same size. For example, if your drive works with 4KB blocks then even the smallest file containing a single byte will still take up 4KB on the disk, as that is the minimum space it can allocate. Once you write out the 4KB + 1 byte it will then allocate another 4KB block of storage, thus making it 8KB on disk. Hence the Size on disk is always a multiple of 4KB. So the fact the source and destination files have the same Size on disk does not mean the files are the same length. (Different drives have different blocks sizes, it is not always 4KB).

The Size value is the actual defined length of the file data within the disk blocks.

Your Size Issue

As your Size values are different it means that the operating system has saved different lengths of data. Hence you have a fundamental problem with your copying routine and not just an issue with the last byte as you think at the moment. One of your files is 3,434 bytes and the other 2,008 which is a big difference. Your first step must be to work out why you have such a big difference.

If your hex comparing routine is simply looking at the block data then it will think they are the same length as it is comparing disk blocks rather than actual file length.

Upvotes: 0

user541686
user541686

Reputation: 210437

Possible answers:

  1. You forgot to call Stream.close() or Stream.Dispose().

  2. Your code is messing up text and and other kinds of data (e.g. casting a -1 from a Read() method into a char, then writing it.

We need to see your code though...

Upvotes: 1

Related Questions