Two identical files have different file size based on the way it is written from C#

c#, encoding, file-io, json, serialization

Solution

Even though the content of both the files are same, they have different file size.

If they have a different size, then they definitely have different contents. A file is (pretty much) just a sequence of bytes - and if two sequences have different lengths, they're different sequences.

In this case, the two files both represent the same text, but using different encodings - `file2` will use UTF-8, and `file1` will use UTF-16.

To think of it a different way: if you saved the same picture to two files, one as JPEG and one as PNG, would you expect the files to be the same size?

Problem

I am trying to write to a file an array of object serialised into JSON format. I am trying to write it in two different way as shown below. ``` ToSerialise[] Obj = new ToSerialise[10]; for (int i = 0; i < 10; i++) { Obj[i] = new ToSerialise(); } //First form of serialising UnicodeEncoding uniEncoding = new UnicodeEncoding(); String SerialisedOutput; SerialisedOutput = JsonConvert.SerializeObject(Obj, Formatting.Indented); FileStream fs1 = new FileStream(@"C:\file1.log", FileMode.CreateNew); fs1.Write(uniEncoding.GetBytes(SerialisedOutput), 0, uniEncoding.GetByteCount(SerialisedOutput)); fs1.Close(); //Second form of serialising FileStream fs2 = new FileStream(@"C:\file2.log", FileMode.CreateNew); StreamWriter sw = new StreamWriter(fs2); JsonWriter jw = new JsonTextWriter(sw); JsonSerializer js = new JsonSerializer(); jw.Formatting = Formatting.Indented; js.Serialize(jw, Obj); jw.Close(); fs2.Close(); ``` Even though the content of both the files are same, they have different file size. Actually the first file is exactly twice the size of the second file. I tried comparing the output using textpad and it says they are excatly the same. Why do they have different file size? I am running this on Windows 7 32 bit, .Net4 Thanks

Original source