Today’s part will be a slight deviation from what I planned last time. I got side-tracked with trying to save the xml file in a compressed format and actually managed to achieve it.
DotNetZip library
Thanks to this open source library it is possible to output the xml generated by the DataSet straight to a zip file – it is not necessary to first save the xml file and then zip it. To achieve this all you need is the following:
private void WriteToZipFile(string zipFilePath, DataSet ds)
{MemoryStream mStream = new MemoryStream();
ds.WriteXml(mStream, XmlWriteMode.WriteSchema);
mStream.Seek(0, SeekOrigin.Begin);if (File.Exists(zipFilePath))
File.Delete(zipFilePath);
using (ZipFile zipFile = new ZipFile(zipFilePath))
{zipFile.CompressionLevel = Ionic.Zlib.CompressionLevel.BestCompression;
zipFile.AddEntry(ds.DataSetName + “.xml”, mStream);
zipFile.Save();}
}
private Stream ReadFromZipFile(string zipFilePath, string dsName)
{MemoryStream mStream = new MemoryStream();
using (ZipFile zipFile = new ZipFile(zipFilePath))
{if ((from z in zipFile.Entries
where z.FileName == dsName + “.xml”
select z).Count() > 0)
{ZipEntry ze = (from z in zipFile.Entries
where z.FileName == dsName + “.xml”
select z).First();ze.Extract(mStream);
mStream.Seek(0, SeekOrigin.Begin);}
}
return mStream;
}
Using it is as simple as this:
DatabaseTest dbt = new DatabaseTest(); // Typed DataSet
…
//Saving
WriteToZipFile(“SomeFileName.zip”, dbt);//Loading
DatabaseTest dbt2 = new DatabaseTest();
dbt2.ReadXml(ReadFromZipFile(“SomeFileName.zip”, dbt.DataSetName), XmlReadMode.IgnoreSchema); //Important to ‘exclude’ the schema for a typed DataSet
Really simple hey? Since xml is very ‘compressionable’ (like most text files) you can save quite a bit on disk space.
Find a copy of it here.
WriteToZipFile(saveFileDialogXml.FileName + ".zip", dbt);
0 Comments.