PageRenderTime 7ms CodeModel.GetById 2ms app.highlight 3ms RepoModel.GetById 1ms app.codeStats 0ms

/WorldView/Utilities/CompressedXml.cs

#
C# | 90 lines | 68 code | 21 blank | 1 comment | 9 complexity | 78494f4630a6d6cafdc05c781276db85 MD5 | raw file
 1using System;
 2using System.IO;
 3using System.IO.Compression;
 4using System.Xml;
 5
 6namespace MoreTerra.Utilities
 7{
 8	class CompressedXml
 9	{
10		// This is only for static functions.
11		private CompressedXml()
12		{
13		}
14
15		public static void LoadXml(Stream inStream, out XmlDocument xmlDoc, Boolean keepOpen = false)
16		{
17			Int32 compressedSize, uncompressedSize;
18
19			xmlDoc = null;
20
21			if (inStream == null)
22				return;
23
24			if ((inStream.ReadByte() != (Int32)'M') || (inStream.ReadByte() != (Int32)'T') ||
25				(inStream.ReadByte() != (Int32)'Z'))
26				return;
27
28			uncompressedSize = inStream.ReadByte();
29			uncompressedSize += (inStream.ReadByte() * 0x100);
30			uncompressedSize += (inStream.ReadByte() * 0x10000);
31			uncompressedSize += (inStream.ReadByte() * 0x1000000);
32
33			compressedSize = inStream.ReadByte();
34			compressedSize += (inStream.ReadByte() * 0x100);
35			compressedSize += (inStream.ReadByte() * 0x10000);
36			compressedSize += (inStream.ReadByte() * 0x1000000);
37
38			if (inStream.Length != (compressedSize + 11))
39				return;
40
41			DeflateStream ds = new DeflateStream(inStream, CompressionMode.Decompress, keepOpen);
42
43			xmlDoc = new XmlDocument();
44			xmlDoc.Load(ds);
45		}
46
47		public static void SaveToMTZ(String inFile, String outFile)
48		{
49			FileStream ifs = new FileStream(inFile, FileMode.Open, FileAccess.Read);
50			FileStream ofs = new FileStream(outFile, FileMode.Create, FileAccess.Write);
51
52			Byte[] buffer = new Byte[11];
53
54			Int64 uncompressedSize = ifs.Length;
55
56			buffer[0] = (Byte)'M';
57			buffer[1] = (Byte)'T';
58			buffer[2] = (Byte)'Z';
59
60			buffer[3] = (Byte)(uncompressedSize & 0xFF);
61			buffer[4] = (Byte)((uncompressedSize & 0xFF00) >> 8);
62			buffer[5] = (Byte)((uncompressedSize & 0xFF0000) >> 16);
63			buffer[6] = (Byte)((uncompressedSize & 0xFF000000) >> 24);
64
65			buffer[7] = 0;
66			buffer[8] = 0;
67			buffer[9] = 0;
68			buffer[10] = 0;
69
70			ofs.Write(buffer, 0, 11);
71
72			DeflateStream ds = new DeflateStream(ofs, CompressionMode.Compress, true);
73			ifs.CopyTo(ds);
74			ds.Flush();
75			ds.Close();
76			ifs.Close();
77
78			ofs.Seek(7, SeekOrigin.Begin);
79
80			Int64 compressedSize = (ofs.Length - 11);
81			buffer[3] = (Byte)(compressedSize & 0xFF);
82			buffer[4] = (Byte)((compressedSize & 0xFF00) >> 8);
83			buffer[5] = (Byte)((compressedSize & 0xFF0000) >> 16);
84			buffer[6] = (Byte)((compressedSize & 0xFF000000) >> 24);
85
86			ofs.Write(buffer, 3, 4);
87			ofs.Close();
88		}
89	}
90}